简体   繁体   中英

How to change font size of Navigation controller back button

I'm attempting to change the font size of a Navigation Controllers back button to no avail.

I'm currently doing this in the previous view controllers viewWillAppear :

 navigationController?.navigationBar.backItem?.backBarButtonItem?.setTitleTextAttributes(
    [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 5)], for: .normal)

The above code does nothing.. So, two questions.

First, what is the correct approach for changing the back buttons font size (which by the way, seems far more difficult than it should be).

Second, is there a singular place (like the AppDelegate) I can make this change so that it affects all view controllers?

You can change it inside AppDelegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "SF Pro Display", size: 17)!], for: .normal)

    return true
}

Where you can customize the font and size of the Navigation bar buttons so it changes in all View Controllers.

I would use UIAppearance protocol to implement this.

First, what is the correct approach for changing the back buttons font size (which by the way, seems far more difficult than it should be).

This depends on the use-case basis. If there is only one navigation bar, I would just change its back button properties by doing something like this.

navigationItem.leftBarButtonItem?.setTitleTextAttributes

but if I want to do a custom button itself, then I would just add a new button here.

Second, is there a singular place (like the AppDelegate) I can make this change so that it affects all view controllers?

if you want to change the entire bar button appearance,

UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: customFont], for: .normal)

I would not do this. It will not be scalable in the longer run. You will definitely have more navigation screens eventually and you would not want them to have the same appearance and then, it would be a bigger refactor!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM