Error when instantiating a UIFont in an text attributes dictionary

后端 未结 4 946
北恋
北恋 2020-12-11 01:58

I\'m trying to set the font of the UIBarButtonItem like so:

let barButton = UIBarButtonItem.appearance()
barButton.setTitleTextAttributes([NSFon         


        
4条回答
  •  無奈伤痛
    2020-12-11 02:15

    The initializer of UIFont returns an optional because it may fail due to misspelled font name etc.

    You have to unwrap it and check:

    if let font = UIFont(name: "AvenirNext", size: 15) {
        barButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
    }
    

    UPDATED for Swift 3

    if let font = UIFont(name: "AvenirNext", size: 15) {
        barButton.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
    }
    

提交回复
热议问题