Change the font of a UIBarButtonItem

2019-01-16 02:33发布

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?

13条回答
ゆ 、 Hurt°
2楼-- · 2019-01-16 02:57

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)
查看更多
可以哭但决不认输i
3楼-- · 2019-01-16 02:57

These are great answers above. Just updating for iOS7:

NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Thin" size:18.0] , NSForegroundColorAttributeName: [UIColor whiteColor]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];
查看更多
Viruses.
4楼-- · 2019-01-16 02:59

In Swift 4, you can change the font and colour of UIBarButtonItem by adding the following code.

addTodoBarButton.setTitleTextAttributes(
        [
        NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
        NSAttributedStringKey.foregroundColor: UIColor.black
        ], for: .normal)
查看更多
淡お忘
5楼-- · 2019-01-16 02:59

Assuming you want to support iOS4 and earlier, your best bet is to create a bar button using the initWithCustomView: method and supply your own view which could be something like a UIButton where you can easily customise the font.

You can also drag a UIButton onto a toolbar or navigation bar in Interface Builder if you want to create the button with drag-and-drop instead of programmatically.

Unfortunately this means creating the button background image yourself. There's no way to customise the font of a standard UIBarButtonItem prior to iOS5.

查看更多
【Aperson】
6楼-- · 2019-01-16 03:01

In Swift you would do this as followed:

backButtonItem.setTitleTextAttributes([
        NSFontAttributeName : UIFont(name: "Helvetica-Bold", size: 26)!,
        NSForegroundColorAttributeName : UIColor.blackColor()],
    forState: UIControlState.Normal)
查看更多
唯我独甜
7楼-- · 2019-01-16 03:03

UIBarButton haven't property related to change the font. But you can create a button with custom font and then add into UIBarButton. It May be solved your problem

查看更多
登录 后发表回答