Error when instantiating a UIFont in an text attributes dictionary

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 06:40:08

问题


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]

}



来源:https://stackoverflow.com/questions/26483671/error-when-instantiating-a-uifont-in-an-text-attributes-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!