如何更改UIBarButtonItems的默认字体?

问题描述 投票:1回答:2

我想为所有UIBarButtonItems更改默认字体。我的应用程序的根视图控制器中有以下代码:

    let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 30)]
    UIBarButtonItem.appearance().setTitleTextAttributes(attributes, for: .normal)
    UINavigationBar.appearance().titleTextAttributes = attributes
    UINavigationBarAppearance().buttonAppearance.normal.titleTextAttributes = attributes
    UIBarButtonItemAppearance().normal.titleTextAttributes = attributes
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "foo", style: .plain, target: nil, action: nil)

尽管外观有所变化,但该栏按钮项目的字体仍是默认字体。如何设置默认字体?我知道我可以为每个单独的按钮按钮设置字体,但是我正在寻找一种广泛更改字体的方法。

ios fonts uibarbuttonitem
2个回答
1
投票

iOS 13之前的版本

class AppDelegate : NSObject, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        if #available(iOS 13, *) {

        }else{
            let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 30)]
            UIBarButtonItem.appearance().setTitleTextAttributes(attributes, for: .normal)
            UINavigationBar.appearance().titleTextAttributes = attributes
        }

        return true
    }
}

iOS 13

class MyNavigationController : UINavigationController {

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
        if #available(iOS 13, *) {
            let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 30)]
            let appearance = UINavigationBarAppearance()
            appearance.buttonAppearance.normal.titleTextAttributes = attributes
            appearance.titleTextAttributes = attributes
            self.navigationBar.standardAppearance = appearance
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

1
投票

您可以使用UINavigationBarAppearance来自定义所有导航栏,但是您需要在导航栏的外观代理上设置standardAppearance-这样的调用:

UINavigationBarAppearance().buttonAppearance.normal.titleTextAttributes = attributes
UIBarButtonItemAppearance().normal.titleTextAttributes = attributes

单独执行任何操作,因为它们会创建一个新外观,设置一个值,然后将其丢弃。而是这样做:

let appearance = UINavigationBarAppearance()
appearance.buttonAppearance.normal.titleTextAttributes = attributes
UINavigationBar.appearance().standardAppearance = appearance
© www.soinside.com 2019 - 2024. All rights reserved.