Change UIBarButtonItem Text Font Size and Color

14,920

Solution 1

Is this what your looking for?

Objective-C:

[buttonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: 
[UIFont fontWithName:@"Helvetica-Bold" size:20.0], NSFontAttributeName,
[UIColor blackColor], NSForegroundColorAttributeName,
nil] forState:UIControlStateNormal];

Swift:

let titleDict: NSDictionary = [NSFontAttributeName: "Helvetica-Bold"]
self.numberToolbar.titleTextAttributes = titleDict

Solution 2

As with all UIBarItem's, you can set the text attributes using:

- (void)setTitleTextAttributes:(NSDictionary *)attributes
                      forState:(UIControlState)state

You can also use tintColor to change the text color.

I would recommend sticking to Apple's style guide in terms of using bold fonts only on the done item.

Share:
14,920
CAN
Author by

CAN

Updated on June 23, 2022

Comments

  • CAN
    CAN almost 2 years

    I would like to know how can I change the text font of the BarButtonItem ? While I could not set the setTitleTextAttributes

    class TextfieldLogin : UITextField {
    
    func INIT(){
        let numberToolbar = UIToolbar(frame: CGRectMake(0,0,320,50))
        numberToolbar.tintColor = UIColor.whiteColor()
        numberToolbar.barTintColor = UIColor(red: 155.0/255, green: 14.0/255, blue: 45.0/255, alpha: 1.0)
    
        numberToolbar.items = [
            UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil),
            UIBarButtonItem(title: "DONE", style: UIBarButtonItemStyle.Plain, target: self, action: "close"),
            UIBarButtonItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(18.0),NSForegroundColorAttributeName : UIColor.redColor(),NSBackgroundColorAttributeName:UIColor.blackColor()],
                forState: UIControlState.Normal)        ]
    
        numberToolbar.sizeToFit()
    
        }
    }
    
  • Anbu.Karthik
    Anbu.Karthik almost 9 years
    can you customize your answer to swift , the questioner need the answer in swift
  • CAN
    CAN almost 9 years
    Thanks @Anbu.Karthik . Yes please I need the answer in Swift.
  • MSU_Bulldog
    MSU_Bulldog almost 9 years
    updated my answer to include Swift, I don't use Swift much so sorry if you need to change it up a little. You get the concept of setting those NavBar TitleTextAttributes though right?
  • CAN
    CAN almost 9 years
    @MSU_Bulldog I can't call navigationController in the UITextField class. Please check
  • MSU_Bulldog
    MSU_Bulldog almost 9 years
    Update my answer: how about that, will that work for you?
  • Alex Zavatone
    Alex Zavatone over 6 years
    Wonderful. Thank you.
  • jcpennypincher
    jcpennypincher almost 6 years
    Make sure you are changing this on the main thread or it will not update.