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

Viewed 82782

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!

10 Answers

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];

I was having this problem too and solved it by using a png file with an alpha channel. I was trying to do a quick mockup and added a back button with a jpg file on a background the default colour of the buttons. I got a white rectangle. But when I created an arrow on a transparent background and saved it as a png file, it worked.

The UIBarbuttonItem initWithImage will not create a bar button with that specified Image. It creates a pattern of a UIBarbutton using the given image. If the specified image is not transparent it will show a bar button with specified tintcolor on it which has the size of the image. If the image has opaque parts then the tint color will be filled on the opaque parts like the default UIBarButtonSystemItemBookmarks.It hase opaque boarder and transparent inner side.

In your case the titncolor is white that is why it shows white.

You are able to create UIBarButtonItem with system standard icons using
- initWithBarButtonSystemItem:target:action:

For example:

[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind target:self action:@selector(YOUR_METHOD:)];
Related