The UIBarButtonItem icon is white when added via IB, black when added programmatically

When I add an icon to UIBarButtonItem through the interface builder, the icon is displayed in white. When I add the same icon file programmatically to another UIToolbar , the icon is displayed in black. Why?

 UIImage *image = [UIImage imageNamed:@"icon.png"]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:image forState:UIControlStateNormal]; rootViewController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:reloadButton] autorelease]; 
+7
iphone cocoa-touch uikit uibarbuttonitem
source share
4 answers

All that Jongsma said is right, you should use the initWithImage: style: message.

The next problem is not how you create the UIBarButtonItem , but where you assigned it. You create it using UIBarButtonItemStylePlain, which usually should display the outline of the icon in white, but rightBarButtonItem UINavigationItem (like the left one) is not allowed UIBarButtonItemStylePlain. It is implicitly converted to UIBarButtonItemStyleBordered. In border style, the icon appears as is, black with a slight gradient.

I think that if you want the element to be white on the border panel, you have to touch the image itself.

+6
source share

Answer. If you want it to be white, paint your image white.

Details:

UIBarButtonItems behave a little differently, depending on how you use them.

When adding to UIToolbar :

initWithImage:style:target:action: creates "white icons" (the color of the image is ignored, opaque pixels are used as a mask to create a white image).
This is true for bordered and plain styles (but only for UIToolbar).

initWithCustomView: Displays a normal color image.

When adding to UINavigationItem :

initWithImage:style:target:action: creates color images and converts plain to bordered .

+6
source share

In your code, you set UIButton as a subpoint of UIBarButtonItem. UIBarButtonItem is already a button, so you should not add another button as a subtitle.

Try the following:

 UIImage *image = [UIImage imageNamed:@"icon.png"]; rootViewController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:image] autorelease]; 
0
source share

There was the same problem. I noticed that @ 2X images were used instead ...

0
source share

All Articles