如何在导航栏上更改UIBarButtonItem的字体颜色/文本颜色

use*_*721 26 iphone xcode objective-c ipad ios

我按照下面的方式在导航栏中添加了一个条形按钮

UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"CANCEL" style:UIBarButtonItemStyleBordered target:self action:@selector(goToPreviousView)];
    self.navigationItem.leftBarButtonItem = cancel;
Run Code Online (Sandbox Code Playgroud)

现在我想在RED Color中显示Text"CANCEL".

我的意思是我需要更改条形按钮项目上文本,而不是按钮的色调颜色.

怎么做?

Iro*_*ill 104

看一下这个 :-

  UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"Title" style:UIBarButtonItemStyleBordered target:nil action:nil];
[cancel setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor redColor],  UITextAttributeTextColor,nil] forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,`UITextAttributeTextColor`在7.0中被替换为`NSForegroundColor`. (5认同)
  • NSForegroundColorAttributeName是UITextAttributeTextColor的正确替代品 (3认同)

Gan*_*ham 33

只是一个带有现代Obj-C语法的iOS7更新:

[barButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)


小智 12

UITextAttributeTextColor //Is deprecated on iOS 7. 
Run Code Online (Sandbox Code Playgroud)

此代码用于从外观代理更改文本颜色.

[[UIBarButtonItem appearance] setTintColor:[UIColor redColor]];
Run Code Online (Sandbox Code Playgroud)


Iro*_*ill 7

另一种方法是: -

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
[button setTitle:@"Delete" forState:UIControlStateNormal];
 button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f];
[button.layer setCornerRadius:4.0f];
[button.layer setMasksToBounds:YES];
[button.layer setBorderWidth:1.0f];
[button.layer setBorderColor: [[UIColor grayColor] CGColor]];
button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0);
[button addTarget:self action:@selector(batchDelete)  forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem* deleteItem = [[UIBarButtonItem alloc] initWithCustomView:button];
Run Code Online (Sandbox Code Playgroud)


Sag*_*ggy 6

这是更新的swift 4.0版本代码:

let reset = UIBarButtonItem(title: "Reset All", style: .plain , target: self, action: #selector(self.resetButtonClicked(_ :) ))
reset.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.red], for: .normal)
Run Code Online (Sandbox Code Playgroud)