Error when instantiating a UIFont in an text attri

2019-01-19 11:42发布

问题:

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

let barButton = UIBarButtonItem.appearance()
barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext", size: 15], forState: UIControlState.Normal)

But it throws a compiler error saying:

Cannot invoke 'init' with an argument list type '($T7, forState: UIControlState)`

and I have no idea what that means. I have also tried

barButton.titleTextAttributesForState(UIControlState.Normal) =[NSFontAttributeName...]` 

but it appears that it isn't assignable

How can I resolve this?

回答1:

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)
}


回答2:

Setting Custom font is little bit tricky, since they don't have font and title properties. Hope this following answer will help you.

let font = UIFont(name: "<your_custom_font_name>", size: <font_size>)
var leftBarButtonItem = UIBarButtonItem(title: "<font_hex_code>", style: UIBarButtonStyle.Plain, target: self, action: "buttonClicked:")
leftBarButtonItem.setTitleTextAttributes([NSFontAttributeName:font!], forState: UIControlState.Normal)
self.navigationItem.leftBarButtonItem = leftBarButtonItem


回答3:

if let font : UIFont = UIFont(name: "Roboto-Regular", size: 15)
        {
            cancelBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
            doneBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)

        }


回答4:

With Swift 4

NSFontAttributeName is deprecated, you can use NSAttributedStringKey values to set attributes.

if let fontStyle = UIFont(name: "HelveticaNeue-Light", size: 19) {
 navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: fontStyle]

}