Change the font of a UIBarButtonItem

前端 未结 16 1137
春和景丽
春和景丽 2020-12-07 09:18

\"UIToolbar

I have a UIBarButtonItem in my UIToolbar titled

16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 10:05

    For those interested in using UIAppearance to style their UIBarButtonItem's fonts throughout the app, it can be accomplished using this line of code:

    Objective C:

    NSDictionary *barButtonAppearanceDict = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:12.0], NSForegroundColorAttributeName: [UIColor whiteColor]};
    [[UIBarButtonItem appearance] setTitleTextAttributes:barButtonAppearanceDict forState:UIControlStateNormal];
    

    Swift 2.3:

    UIBarButtonItem.appearance().setTitleTextAttributes(
    [
        NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
        NSForegroundColorAttributeName : UIColor.white
    ],
    for: .normal)
    

    Swift 3

    UIBarButtonItem.appearance().setTitleTextAttributes(
    [
        NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: 12)!,
        NSForegroundColorAttributeName : UIColor.white,
    ], for: .normal)
    

    Swift 4

    UIBarButtonItem.appearance().setTitleTextAttributes(
    [
        NSAttributedStringKey.font : UIFont(name: "HelveticaNeue-Light", size: 12)!,
        NSAttributedStringKey.foregroundColor : UIColor.white,
    ], for: .normal)
    

    Or for a single UIBarButtonItem (not for all app wide), if you have a custom font for one button in particular:

    Swift 3

    let barButtonItem = UIBarButton()
    barButtonItem.setTitleTextAttributes([
        NSFontAttributeName : UIFont(name: "FontAwesome", size: 26)!,
        NSForegroundColorAttributeName : UIColor.white,
    ], for: .normal)
    barButtonItem.title = "\u{f02a}"
    

    Swift 4

    let barButtonItem = UIBarButton()
    barButtonItem.setTitleTextAttributes([
        NSAttributedStringKey.font : UIFont(name: "FontAwesome", size: 26)!,
        NSAttributedStringKey.foregroundColor : UIColor.white,
    ], for: .normal)
    barButtonItem.title = "\u{f02a}"
    

    Of course, you can change the font & size to whatever you'd like. I prefer to put this code in the AppDelegate.m file in the didFinishLaunchingWithOptions section.

    Available attributes (just add them to the NSDictionary):

    • NSFontAttributeName: Change font with a UIFont
    • NSForegroundColorAttributeName: Change color with a UIColor
    • NSShadow: Add a drop shadow (see NSShadow class reference)

    (Updated for iOS7+)

提交回复
热议问题