2

I have an application's navigation bar set in the AppDelegate. In one of my ViewController's I'm trying to set the attributes differently - they work however when I get to other VC's the still persist.

What is the correct way to implement this?

AppDelegate.swift

UINavigationBar.appearance().titleTextAttributes = [
        NSFontAttributeName: UIFont(name: "MuseoSans-500", size: 19)!,
        NSForegroundColorAttributeName: UIColor.white
    ]
    UINavigationBar.appearance().tintColor = UIColor.white

SharkViewController.swift

// MARK: - View Did Load
override func viewDidLoad() {
    super.viewDidLoad()

    UINavigationBar.appearance().titleTextAttributes = [
        NSFontAttributeName: UIFont(name: "MuseoSans-500", size: 19)!,
        NSForegroundColorAttributeName: UIColor.black
    ]
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
pjmanning
  • 1,241
  • 1
  • 20
  • 48

3 Answers3

7

Do it in your viewWillAppear:

UINavigationBar.appearance().titleTextAttributes = [
    NSFontAttributeName: UIFont(name: "MuseoSans-500", size: 19)!,
    NSForegroundColorAttributeName: UIColor.black
]

And then when you leave the view, in your viewWillDisappear, you just reset the orgiginal value.

Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • I tried to set `navigationController?.navigationBar.standardAppearance` with this way and it works even with animation! – Gargo Jul 28 '23 at 11:41
1

The best way is to change the appearance of the navigationItem of your viewController:

let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.font: UIFont(name: "MuseoSans-500", size: 19)!]
navigationItem.standardAppearance = appearance

This will change only your viewController appearance and you can do it either in the viewDidLoad or viewWillAppear.

floydaddict
  • 1,147
  • 1
  • 7
  • 5
-1

You also can use on viewDidLoad: or viewWillAppear the following code:

self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "MuseoSans-500", size: 19)!,
                                                                    NSForegroundColorAttributeName: UIColor.black]
Alfredo Luco G
  • 876
  • 7
  • 18
  • 2
    `viewDidLoad:` isn't enough because it won't get called the next time the user navigates to that view controller, such as via a back button or unwind segue. – NRitH Jun 21 '17 at 17:35