简体   繁体   English

iOS:无法更改UIBarButtonItem的颜色

[英]iOS: Can't change the color of a UIBarButtonItem

I basically have a ViewController that is the root ViewController of a UINavigationController. 我基本上有一个ViewController,它是UINavigationController的根ViewController。 Basically I have a UIBarButtonItem that when a user presses on it, its tint color should toggle between red and green. 基本上我有一个UIBarButtonItem,当用户按下它时,其色调颜色应在红色和绿色之间切换。 But the color doesn't seem to change. 但是颜色似乎并没有改变。 My code: 我的代码:

@interface TestButtonColorViewController (){
    BOOL colorMode;
}
@end

@implementation TestButtonColorViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    colorMode = NO;

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Change" style:UIBarButtonItemStyleBordered target:self action:@selector(changeColor)];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)changeColor{
    colorMode = !colorMode;

    if (colorMode) {
        [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:[UIColor redColor]];
    }
    else {
        [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:[UIColor greenColor]];
    }
}

As CSmith has suggested, you should set the tint directly: 正如CSmith所建议的,您应该直接设置色调:

- (void)changeColor {
    colorMode = !colorMode;

    if (colorMode) {
        [self.navigationItem.rightBarButtonItem setTintColor:[UIColor redColor]];
    } else {
        [self.navigationItem.rightBarButtonItem setTintColor:[UIColor greenColor]];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM