Reputation: 2439
I want to change the default font for all UIBarButtonItems. I have the following code in the root view controller of my app:
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)
That bar button item's font is still the default, despite the appearance changes. How can I set a default font? I know I can set the font for each individual bar button item, but I'm looking for a way to change it broadly.
Upvotes: 1
Views: 141
Reputation: 151
You can use UINavigationBarAppearance to customize all navigation bars, but you need to set the standardAppearance on the navigation bar's appearance proxy – calls like these:
UINavigationBarAppearance().buttonAppearance.normal.titleTextAttributes = attributes
UIBarButtonItemAppearance().normal.titleTextAttributes = attributes
in isolation do nothing, as they create a new appearance, set a value, then throw it away. Instead do this:
let appearance = UINavigationBarAppearance()
appearance.buttonAppearance.normal.titleTextAttributes = attributes
UINavigationBar.appearance().standardAppearance = appearance
Upvotes: 1
Reputation: 194
iOS 13 before
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")
}
}
Upvotes: 1