我该如何更改UIBarButton项目的字体颜色?

23

我想把颜色改为红色。


可能是重复的问题:带颜色的UIBarButtonItem? - memmons
6个回答

104

我找到了一种更简单的方法来改变标题的颜色: iOS7:

UIBarButtonItem *button = 
 [[UIBarButtonItem alloc] initWithTitle:@"Title" 
                                  style:UIBarButtonItemStyleBordered 
                                 target:nil 
                                 action:nil];
[button setTitleTextAttributes:
          [NSDictionary dictionaryWithObjectsAndKeys: 
               [UIColor redColor], NSForegroundColorAttributeName,nil] 
                                            forState:UIControlStateNormal];

在 iOS7 之前:

UIBarButtonItem *button = 
  [[UIBarButtonItem alloc] initWithTitle:@"Title" 
                                   style:UIBarButtonItemStyleBordered 
                                  target:nil 
                                  action:nil];
[button setTitleTextAttributes:
          [NSDictionary dictionaryWithObjectsAndKeys: 
               [UIColor redColor], UITextAttributeTextColor,nil] 
                                    forState:UIControlStateNormal];

2
如果你使用的是iOS 5.0或更高版本,这绝对是一个不错的解决方案。OP:详细信息请查看UIBarItem.h。 - gschandler
我已经搜索了很长时间,想找出如何更改文本颜色,非常感谢!!幸运的是,现在大多数手机都在使用IOS5,所以这并不是一个真正的问题。 - AdamM
我已经修复了这个答案,针对iOS7。 - Mirko Brunner
适用于iOS7。谢谢,伙计! - Robert J. Clegg
谢谢@Gavy,它运行得很好。你能告诉我如何更改标题的字体吗? - Anand Gautam
@AnandGautam 你可以使用UITextAttributeFont属性来更改字体。 - Gavy

9

这个问题在这里得到了解答。基本上,您需要创建一个UIButton,按照您的意愿进行配置,然后使用UIButton作为自定义视图初始化Bar Button Item。


8
有两种方法可以改变显示UIBarButtonITem的文本颜色。
1)
[barButtonITem setTintColor:[UIColor redColor]];

2) 或者你可以使用任何UIColor类方法。这是一种非常有效的解决方案。尽管对于iOS 7,您可以使用NSForegroundColorAttributeName。

barButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor clearColor],NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];

3

在 Guvvy Ava 的类似提示下,您可以像这样更改字体大小:

[buttonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica-Bold" size:26.0], UITextAttributeFont,nil] forState:UIControlStateNormal];

2

要求使用 Swift 版本 4.0 或更高版本

barButtonITem.tintColor = UIColor.red   // for textColor change

如果想要改变字体和文字颜色,请使用以下代码。
barButtonITem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor :UIColor.red,NSAttributedStringKey.font:UIFont.init(name:"Avenir", size:15.0)], for: UIControlState.normal)

0
如果您正在使用系统导航栏按钮项,则要更改按钮色调颜色,请使用以下方法:
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

要改变按钮文本颜色,也可以使用以下代码。

[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];

在你想要改变颜色的视图控制器中添加以下代码行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接