本文介绍了在文本属性字典中实例化 UIFont 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试像这样设置 UIBarButtonItem
的字体:
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:
无法使用参数列表类型 '($T7, forState: UIControlState)` 调用 'init'
我不知道那是什么意思.我也试过
and I have no idea what that means. I have also tried
barButton.titleTextAttributesForState(UIControlState.Normal) =[NSFontAttributeName...]`
但它似乎不可分配
我该如何解决这个问题?
How can I resolve this?
推荐答案
UIFont
的初始值设定项返回一个可选项,因为它可能会因字体名称拼写错误等而失败.
The initializer of UIFont
returns an optional because it may fail due to misspelled font name etc.
你必须打开它并检查:
if let font = UIFont(name: "AvenirNext", size: 15) {
barButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
}
针对 Swift 3 进行了更新
if let font = UIFont(name: "AvenirNext", size: 15) {
barButton.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
}
这篇关于在文本属性字典中实例化 UIFont 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!