How to set the navigation bar's back bar button without using UIBarButtonItem.appearance

Viewed 19

I have a custom UINavigationController like so:

class CustomNavigationController: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        delegate = self
        setupDefaultAppearance()
    }
    
    private func setupDefaultAppearance() {
        UINavigationBar.appearance().tintColor = R.color.textBlack()
        
        let titleAttributes: [NSAttributedString.Key: Any] = [ .font: R.font.interMedium(size: 18)! ]
        UINavigationBar.appearance().titleTextAttributes = titleAttributes
        
        // Hide the title in bar button items
        let backButtonAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont(name: "Helvetica-Bold", size: 0.1)!,
                                                                    .foregroundColor: UIColor.clear]

        UIBarButtonItem.appearance().setTitleTextAttributes(backButtonAttributes, for: .normal)
        UIBarButtonItem.appearance().setTitleTextAttributes(backButtonAttributes, for: .highlighted)
    }
}

However, the code to hide the title in bar button items screwed IQKeyboardManager. The Done button (or any button on the toolbar) in the keyboard or any picker view is gone now because of this. So, I believe I should not use the UIBarButtonItem.appearance() static func. How do I remove the title of the Navigation Controller's back button without making the bug in the keyboard and picker views?

Thanks.

1 Answers

So I've asked the same question to the Apple Developer Forums too. And someone did answered it. Basically, all I need to do is just the appearance is it is contained in the navigation bar like so:

    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes(backButtonAttributes, for: .normal)
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).setTitleTextAttributes(backButtonAttributes, for: .highlighted)
Related