如何仅更改一个 BarButtonItem 的字体大小?

How to change font size of only one BarButtonItem?

我在另一个线程中找到了这段代码,但我只想更改一个按钮的字体大小。

if let font = UIFont(name: "AvenirNext", size: 15) {
oneBarButtonItem.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)}

那么我必须将代码放在哪里,这样正确吗?

您需要将此代码放入 ViewControllerviewDidLoad 方法中。

override func viewDidLoad() {
    super.viewDidLoad()

    let font = UIFont.systemFontOfSize(20);
    barButtonItem.setTitleTextAttributes([NSFontAttributeName: font], forState:UIControlState.Normal)
}

您的代码可能无法运行,因为您没有名为 AvenirNext.

的字体

更新

Swift4 / iOS11 的工作代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let font = UIFont.systemFont(ofSize: 20)
    barButtonItem.setTitleTextAttributes([NSAttributedStringKey.font.rawValue: font], forState: .normal)
}

对于Objective C,

 [barbutton setTitleTextAttributes:@{
                                     NSFontAttributeName: [UIFont fontWithName:@"Helvetica-Bold" size:13.0],
                                     NSForegroundColorAttributeName: [UIColor whiteColor]
                                     } forState:UIControlStateNormal];