Change the font of a UIBarButtonItem

Ankit Vyas picture Ankit Vyas · Jan 13, 2012 · Viewed 86.9k times · Source

UIToolbar with UIBarButtonItem

I have a UIBarButtonItem in my UIToolbar titled Done. Now I want to change the font from the default to "Trebuchet MS" with Bold. How can I do that?

Answer

mask picture mask · Oct 1, 2012

To be precise, this can be done as below

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

Or with object literal syntax:

[buttonItem setTitleTextAttributes:@{
     NSFontAttributeName: [UIFont fontWithName:@"Helvetica-Bold" size:26.0],
     NSForegroundColorAttributeName: [UIColor greenColor]
} forState:UIControlStateNormal];

For convenience, here's the Swift implementation:

buttonItem.setTitleTextAttributes([
        NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 26.0)!,
        NSAttributedStringKey.foregroundColor: UIColor.green],
    for: .normal)