Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add image to UIBarButtonItem using initWithImage:(UIImage *)image

I would like to know how to set an image to a UIBarButtonItem which will then be added to a UIToolbar, by using InitWithImage when creating a UIBarButtonItem.

I am doing the following, but it creates a blank whitespace where the image should be on the UIToolbar

UIImage *image = [UIImage imageNamed:@"6.png"];  UIBarButtonItem *systemItem1 = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(pp:)]; 

Thank You!

like image 529
Shumais Ul Haq Avatar asked Jul 21 '10 14:07

Shumais Ul Haq


2 Answers

And for iOS 7+ you do the following:

Objective-C

 UIImage *image = [[UIImage imageNamed:@"myImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];  UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD:)]; 

Swift 2.3

 let image = UIImage(named: "myImage")?.imageWithRenderingMode(.AlwaysOriginal)  let button = UIBarButtonItem(image: image, style: .Plain, target: self, action: #selector(YOUR_METHOD(_:))) 

Swift 3.0

let image = UIImage(named: "myImage")?.withRenderingMode(.alwaysOriginal) let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(YOUR_METHOD(_:))) 
like image 174
Vahan Avatar answered Sep 28 '22 05:09

Vahan


Here's an example that creates a toolbar button from the Facebook logo. Create a pointer to an image (file already added to xCode), create a custom button, change the size of the button to match the image, set image of button, create toolbar button from button view.

UIImage *faceImage = [UIImage imageNamed:@"facebook.png"]; UIButton *face = [UIButton buttonWithType:UIButtonTypeCustom]; face.bounds = CGRectMake( 0, 0, faceImage.size.width, faceImage.size.height ); [face setImage:faceImage forState:UIControlStateNormal]; UIBarButtonItem *faceBtn = [[UIBarButtonItem alloc] initWithCustomView:face]; 
like image 37
Kwexi Avatar answered Sep 28 '22 06:09

Kwexi