在Swift中定制UIBarButtonItem
我试图在AppDelegate
设置UIBarButtonItem
的字体,如下UIBarButtonItem
:
let barButton = UIBarButtonItem.appearance() barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext", size: 15], forState: UIControlState.Normal)
但它引发了一个编译器错误说:
Cannot invoke 'init' with an argument list type '($T7, forState: UIControlState)
我不知道这意味着什么
我也试过了
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: "<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
if let font : UIFont = UIFont(name: "Roboto-Regular", size: 15) { cancelBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal) doneBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal) }