Reputation: 131
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;
});
});
I need to implement the same as the image.What I' doing wrong,please anybody help me to fix this.
Upvotes: 0
Views: 3230
Reputation: 619
Here's oxigen's (excellent) answer converted to Swift 3 / Swift 4:
override func viewDidLoad()
{
super.viewDidLoad()
let url = URL(string: "https://i.sstatic.net/EbYBY.jpg")!
let data = try! Data(contentsOf: url)
let img = UIImage(data: data)
let imageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
imageView.image = img?.withRenderingMode(.alwaysOriginal)
imageView.layer.cornerRadius = 20.0
imageView.layer.masksToBounds = true
let barButton = UIBarButtonItem(customView: imageView)
navigationItem.setLeftBarButton(barButton, animated: false)
}
(The given URL is dead now, but with a proper URL, or other image, the code should work.)
Upvotes: 8
Reputation: 6263
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;
}
Upvotes: 4
Reputation: 2419
You can make the button round by using this
UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,100,100)//set your frame's size
[btn setImage:[UIImage imageNamed:btnImage] forState:UIControlStateNormal];
btn.layer.masksToBounds = NO;
btn.layer.cornerRadius = btn.bounds.size.width/2;;
UIBarButtonItem * btnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
[self.navigationItem setRightBarButtonItems:@[btnItem]];
Upvotes: 0