objective-cuinavigationbaruibarbuttonitemuinavigationitemios8.3

How to place profile image on uibarbuttonitem with rounded corners in objective c?


I want to make my UIbarbuttonItem with rounded corners (the right). I referred the link to implement still I'm not getting.The image comes from URL.My code is,

 dispatch_async(dispatch_get_global_queue(0,0), ^{

 NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL   URLWithString:userImage]];
    if ( data == nil )
        return;
    dispatch_async(dispatch_get_main_queue(), ^{
        // WARNING: is the cell still using the same data by this point??
        UIImage *img = [UIImage imageWithData: data];

        UIImage *btnImage = [self imageWithImage:img scaledToSize:CGSizeMake(50, 50)];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        // btn.bounds = CGRectMake( 0, 0, btnImage.size.width, btnImage.size.height );
        [btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchDown];
        [btn setImage:btnImage forState:UIControlStateNormal];
        UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        self.navigationItem.rightBarButtonItem = btnItem;
    });

});

enter image description here I need to implement the same as the image.What I' doing wrong,please anybody help me to fix this.


Solution

  • It works for me:

    - (void)viewDidLoad
     {
     [super viewDidLoad];
      NSString* url = @"https://i.sstatic.net/EbYBY.jpg";
     NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL   URLWithString:url]];
    UIImage* img = [UIImage imageWithData:data];
    
    UIImageView* v = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    v.image = img;
    v.layer.masksToBounds = YES;
    v.layer.cornerRadius = 20;
    
    UIBarButtonItem* rightBtn = [[UIBarButtonItem alloc] initWithCustomView:v];
    self.navigationItem.rightBarButtonItem = rightBtn;
    }
    

    enter image description here