UIBarButtonItem icon white when added via IB, black when added programmatically
When I add an icon to a UIBarButtonItem
via the Interface Builder, the icon is displayed white. When I add the same icon file programmatically to another UIToolbar
, the icon is displayed black. Why?
UIImage *image = [UIImage imageNamed:@"icon.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:image forState:UIControlStateNormal];
rootViewController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem a开发者_运维百科lloc] initWithCustomView:reloadButton] autorelease];
Everything Jongsma said is right, you should use the initWithImage:style: message.
The next problem is not the way you create the UIBarButtonItem
, but the place you assign it. You create it with UIBarButtonItemStylePlain, which should normally render the icon's outline in white, but the rightBarButtonItem of a UINavigationItem (just like the left) is not allowed the UIBarButtonItemStylePlain. It's implicitly converted to UIBarButtonItemStyleBordered. In the bordered style the icon is rendered 'as is', which is black with a slight gradient.
I think if you want the item in white on a bordered barButton, you'll have to touch the image itself.
Answer: If you want it white, color your image white.
Details:
UIBarButtonItems behave a little differently depending on how you use them.
When adding to a UIToolbar
:
initWithImage:style:target:action:
creates "white icons" (image color is ignored, opaque pixels are used as a mask to create a white image).
This is true for bordered
and plain
styles (but on UIToolbar only).
initWithCustomView:
displays normal colored image.
When adding to a UINavigationItem
:
initWithImage:style:target:action:
creates colored images and converts plain
to bordered
.
In your code, you are setting an UIButton as the subview of an UIBarButtonItem. UIBarButtonItem is already a button, so you shouldn't add another button as the subview.
Try this:
UIImage *image = [UIImage imageNamed:@"icon.png"];
rootViewController.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:image] autorelease];
Had the same problem. I Noted that the @2X images were used instead...
精彩评论