Ios 如何更改UIBarButtonims的默认字体?

Ios 如何更改UIBarButtonims的默认字体?,ios,fonts,uibarbuttonitem,Ios,Fonts,Uibarbuttonitem,我想更改所有UIBarButtonims的默认字体。我的应用程序的根视图控制器中有以下代码: let attributes: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 30)] UIBarButtonItem.appearance().setTitleTextAttributes(attributes, for: .normal) UINavigationBar.appearance

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

    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 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")
    }
}

您可以使用UINavigationBarAppearance自定义所有导航栏,但需要在导航栏的外观代理上设置standardAppearance–调用如下:

UINavigationBarAppearance().buttonAppearance.normal.titleTextAttributes = attributes
UIBarButtonItemAppearance().normal.titleTextAttributes = attributes
孤立地说,他们什么也不做,因为他们创建了一个新的外观,设置了一个值,然后扔掉它。而是这样做:

let appearance = UINavigationBarAppearance()
appearance.buttonAppearance.normal.titleTextAttributes = attributes
UINavigationBar.appearance().standardAppearance = appearance