简体   繁体   中英

How can I change the font color of a UIBarButton item?

我想将颜色更改为红色。

I found a simpler way to just change the color of title: iOS7:

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

and prior iOS7:

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

There are Two ways to change the color of the Text displayed UIBarButtonITem.

1)

[barButtonITem setTintColor:[UIColor redColor]];

2) or you can you any UIColor class method. this is really efficient solution.Althought for iOS 7 you can use NSForegroundColorAttributeName and can use

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

This question was answered here . Basically, you have to create a UIButton, configure it as you wish, and then initialize the Bar Button Item with the UIButton as a custom view.

在Guvvy Ava的类似说明中,您可以更改字体大小

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

swift version 4.0 or later

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

if want to change font as well as text color use the following code

barButtonITem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor :UIColor.red,NSAttributedStringKey.font:UIFont.init(name:"Avenir", size:15.0)], for: UIControlState.normal)

If you are using system Navigation bar button item then to change your button tint color use

self.navigationController.navigationBar.tintColor = [UIColor whiteColor];

To change button text color use the following code also.

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

Add the following line of code which viewcontroller you want to change your color

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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