在文本属性字典中实例化UIFont时出错
我正在尝试设置UIBarButtonItem
的字体, UIBarButtonItem
所示:
let barButton = UIBarButtonItem.appearance() barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext", size: 15], forState: UIControlState.Normal)
但是它会抛出一个编译错误:
无法使用参数列表类型’($ T7,forState:UIControlState)`调用’init’
我不知道这意味着什么。 我也试过了
barButton.titleTextAttributesForState(UIControlState.Normal) =[NSFontAttributeName...]`
但似乎它不可转让
我该如何解决这个问题?
UIFont
的初始化UIFont
返回一个可选项,因为它可能因拼写错误的字体名称而失败等。
你必须打开它并检查:
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) }
设置自定义字体有点棘手,因为它们没有font
和title
属性。 希望以下答案对您有所帮助。
let font = UIFont(name: "", size: ) var leftBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonStyle.Plain, target: self, action: "buttonClicked:") leftBarButtonItem.setTitleTextAttributes([NSFontAttributeName:font!], forState: UIControlState.Normal) self.navigationItem.leftBarButtonItem = leftBarButtonItem
if let font : UIFont = UIFont(name: "Roboto-Regular", size: 15) { cancelBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal) doneBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal) }
使用Swift 4
不推荐使用NSFontAttributeName,可以使用NSAttributedStringKey值来设置属性。
if let fontStyle = UIFont(name: "HelveticaNeue-Light", size: 19) { navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: fontStyle]
}