在NavigationController中更改UIButton的颜色

时间:2016-01-15 17:04:44

标签: ios objective-c uinavigationcontroller uibutton

我设置了NavigationBar的标题并使用以下代码更改了它的颜色:

self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.title = @"SHARE";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.edgesForExtendedLayout =UIRectEdgeNone;

如您所见,条形颜色为黑色,标题颜色为白色。现在我想添加一个按钮给对了。按钮已成功添加,但它没有更改颜色。

UIButton *forwdButton = [[UIButton alloc] init];
    forwdButton.titleLabel.text = @"Send";
    [forwdButton.titleLabel setTintColor:[UIColor whiteColor]];
    [forwdButton setShowsTouchWhenHighlighted:TRUE];
    [forwdButton addTarget:self action:@selector(someMethod) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *barFrwdItem = [[UIBarButtonItem alloc] initWithCustomView:forwdButton];
    self.navigationItem.hidesBackButton = TRUE;

    self.navigationItem.rightBarButtonItem = barFrwdItem;

在这段代码中,我在这些方面遇到了问题:

forwdButton.titleLabel.text = @"Send";
        [forwdButton.titleLabel setTintColor:[UIColor whiteColor]];

它仍显示黑色按钮。它没有改变它的颜色。
我试图做以下事情:

[barFrwdItem setTintColor:[UIColor whiteColor]]; //Which is the UIBarButtonItem

以及

[forwdButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; // which is the UIButton

2 个答案:

答案 0 :(得分:1)

您正在以错误的方式添加按钮。请按此添加右键。

UIBarButtonItem *chkmanuaaly = [[UIBarButtonItem alloc]initWithTitle:@"Send" style:UIBarButtonItemStylePlain target:self action:@selector(someMethod)];
self.navigationItem.rightBarButtonItem=chkmanuaaly;

之后添加此行以更改颜色

[chkmanuaaly setTitleTextAttributes:
          [NSDictionary dictionaryWithObjectsAndKeys: 
               [UIColor whiteColor], UITextAttributeTextColor,nil] 
                                    forState:UIControlStateNormal];
[UINavigationBar appearance].tintColor = [UIColor whiteColor];

答案 1 :(得分:0)

如果您只是想创建一个UIBarButtonItem并让它响应一个动作,那么您不一定需要创建一个子视图。

UIBarButtonItem *forwardButton = [[UIBarButtonItem alloc] initWithTitle:@"Send" style:UIBarButtonItemStylePlain target:self action:@selector(someMethod:)];

从这里您可以在UIBarButton上设置色调颜色,或者如果您希望将UINavigationController上的所有按钮设置为相同的颜色,您可以在导航栏上设置色调颜色。

[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

[forwardButton setTintColor:[UIColor whiteColor];