views:

242

answers:

2

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 alloc] initWithCustomView:reloadButton] autorelease];
A: 

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];
Jongsma
`UIBarButtonItem` does not respond to `initWithImage:` but to `initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(action)`However, the image is still black instead of white.
tob
I'm sorry, that's what I meant indeed.Strange... What is the actual color of the image file?
Jongsma
It's configuration02.png from http://www.greepit.com/open-source-icons-gcons/open-source-icons.zip (Folder PNG/black)
tob
Any further suggestions?
tob
+1  A: 

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.

tonklon
But why is the image displayed in white when I add it via Interface Builder?
tob
You are adding it as rightBarButtonItem via InterfaceBuilder? That appears black when I test it.
tonklon
The image appears white, if the `UIBarButtonItemStylePlain` is used, it appears black with a button around it, with the `UIBarButtonItemStyleBordered`
tonklon