通过外观代理设置UIBarButtonItem的文本颜色

时间:2014-01-10 21:31:24

标签: ios iphone objective-c uikit

这是设置的内容,它接近我需要的颜色:

NSDictionary *barButtonItemTitleAttributesEnabled = @{
                                               NSFontAttributeName:[UIFont MRFontLightOfSize:17],
                                               NSForegroundColorAttributeName:[UIColor whiteColor]
                                               };
NSDictionary *barButtonItemTitleAttributesDisabled = @{
                                                      NSFontAttributeName:[UIFont MRFontLightOfSize:17],
                                                      NSForegroundColorAttributeName:[UIColor colorWithWhite:1.0f alpha:0.25f]
                                                      };

[[UIBarButtonItem appearance] setTitleTextAttributes:barButtonItemTitleAttributesEnabled forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes:barButtonItemTitleAttributesDisabled forState:UIControlStateDisabled];

但我更愿意以某种方式将禁用的文本颜色设置为与所选状态相同的颜色,有没有办法通过外观代理调用来实现?

还试过这个:

NSDictionary *barButtonItemDisabled = [[UIBarButtonItem appearance] titleTextAttributesForState:UIControlStateSelected];
[[UIBarButtonItem appearance] setTitleTextAttributes:barButtonItemTitleAttributesEnabled forState:UIControlStateNormal];
[[UIBarButtonItem appearance] setTitleTextAttributes:barButtonItemDisabled forState:UIControlStateDisabled];

2 个答案:

答案 0 :(得分:4)

通过删除上面的TextTitleAttribute代码并设置toolBar tintColor外观代理来解决:

[[UIToolbar appearance] setTintColor:[UIColor whiteColor]];

这使得只需启用或禁用按钮就可以将它们设置为正确的颜色。

答案 1 :(得分:1)

如果您想为不同的商品提供不同的颜色,那么您应该使用

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Done" style:UIBarButtonItemStylePlain
                                   target:self action:@selector(done)];

[doneButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor],  NSForegroundColorAttributeName,nil] forState:UIControlStateNormal]; 

否则你应该只写

[toolBar setTintColor:[UIColor whiteColor]];