UIBarButtonItem 图标通过 IB 添加时为白色,以编程方式添加时为黑色

人气:740 发布:2022-10-16 标签: iphone cocoa-touch uikit uibarbuttonitem

问题描述

当我通过 Interface Builder 向 UIBarButtonItem 添加图标时,图标显示为白色.当我以编程方式将相同的图标文件添加到另一个 UIToolbar 时,图标显示为黑色.为什么?

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

推荐答案

Jongsma 说的都对,你应该使用 initWithImage:style: 消息.

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

下一个问题不是您创建 UIBarButtonItem 的方式,而是您分配它的位置.您使用 UIBarButtonItemStylePlain 创建它,它通常应该将图标的轮廓呈现为白色,但 UINavigationItem 的 rightBarButtonItem(就像左侧一样)不允许使用 UIBarButtonItemStylePlain.它被隐式转换为 UIBarButtonItemStyleBordered.在带边框的样式中,图标按原样"呈现,即带有轻微渐变的黑色.

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.

我认为,如果您希望在有边框的 barButton 上显示白色项目,则必须触摸图像本身.

I think if you want the item in white on a bordered barButton, you'll have to touch the image itself.

450