在我的导航栏上,我有几个具有自定义图标的 rightBarButtonItems(图标图像是白色的,这与 iOS 6 的基本配色方案配合得很好)。
在 iOS 7 下,使用 initWithTitle 加载图像(参见代码片段 1)将图标中的“白色”颜色替换为适当的全局色调(在本例中为特定的深蓝色)
代码片段 1:
UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:(UIBarButtonItemStyle) UIBarButtonSystemItemCancel target:(self) action:@selector(refreshList)];
refreshButton.image = [UIImage imageNamed:@"RefreshIcon.png"];
但是,我需要使用 initWithCustomView 来克服导致图标移出 View 的奇怪行为变化。基本思想是专门设置图标的大小。 initWithCustomView 解决了大小问题,但不显示具有全局色调的按钮图像,它们以图像的颜色(白色)显示。代码片段 2 展示了我如何使用 initWithCustomView 创建按钮。
代码片段 2:
CGRect frameCustomButton2 = CGRectMake(0.0, 0.0, 18.0, 18.0);
UIButton *customButton2 = [[UIButton alloc] initWithFrame:frameCustomButton2];
[customButton2 setBackgroundImage:iconRefreshButton forState:UIControlStateNormal];
UIBarButtonItem *barCustomButton2 =[[UIBarButtonItem alloc] initWithCustomView:customButton2 ];
barCustomButton2.image = iconRefreshButton;
[customButton2 addTarget:self action:@selector(refreshList) forControlEvents:UIControlEventTouchUpInside];
所有这些代码当然都在 (void)viewDidLoad 中。我尝试过类似的事情:
barCustomButton2.tintColor = [UIColor blackColor]; //doesn't work
或者 [barButtonAppearance setTintColor:[UIColor blackColor]];//不起作用
并且它们不会覆盖图像的白色。这几乎就像自定义 View 的创建发生在 View 查看全局色调颜色之后?
如何确保按钮图标采用全局色调?
Cảm ơn!
只是想将其放入根评论中,以便为“答案”复选标记提供更好的上下文,并提供更好的格式。
我能弄清楚这个!您可以告诉图像始终呈现为模板,这将强制它采用全局色调颜色。
UIImage *iconRefreshButton = [UIImage imageNamed:@"MyIconFilename.png"];
iconRefreshButton = [iconRefreshButton imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
如果您不设置它,默认值为“UIImageRenderingModeAutomatic”,这意味着它将根据上下文呈现为模板或原始图像。
Tôi là một lập trình viên xuất sắc, rất giỏi!