UINavigationBar titleTextAttributes not updated after coming back from a View Controller
Asked Answered
M

2

13

I'm using a UINavigationController to display some view controllers. I need to change the color of the navigation bar title every time I switch between two view controllers. This is what I'm doing now:

First View Controller

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.navigationController.navigationBar.titleTextAttributes = 
         @{
              NSForegroundColorAttributeName: [UIColor whiteColor],
              NSFontAttributeName: [UIFont systemFontOfSize:14.0]
         };
}

Second View Controller

- (void)viewDidLoad:(BOOL)animated
{
    [super viewDidLoad:animated];

    self.navigationController.navigationBar.titleTextAttributes = 
         @{
              NSForegroundColorAttributeName: [UIColor blackColor],
              NSFontAttributeName: [UIFont systemFontOfSize:14.0]
         };
}

The first time I load First VC and when I push Second VC, the title color is handled correctly. The problem here is that when I pop from Second to First view controller, the title is still black, even if viewWillAppear is called correctly and, if I print self.navigationController.navigationBar.titleTextAttributes, the values seems to be updated (NSForegroundColorAttributeName is white).

Magnetic answered 26/4, 2018 at 8:31 Comment(2)
did you try code in viewdidAppear?Blinny
@PiyushSinroja yes, nothing differentMagnetic
A
3

Maybe because of the push/pop transition animation, values are not reflecting. Try calling it this way.

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    dispatch_async(dispatch_get_main_queue(), ^{
        self.navigationController.navigationBar.titleTextAttributes =
        @{
            NSForegroundColorAttributeName: [UIColor blackColor],
            NSFontAttributeName: [UIFont systemFontOfSize:14.0]
        };
    });
}    
Ale answered 26/4, 2018 at 11:33 Comment(2)
If i call it like that, it works, but there's a very noticeable delay and you can see the old format transition to the new. I resolved it by setting the title back to nil on viewDidDisappear, and only setting the title again after the format is applied in viewDidAppearMejias
Settng to nil works. Just wanted to add that you can set title to nil and then back to your title text in consecutive lines to keep the crazy in one place.Axis
G
1

if you are using UINavigationBarAppearance, set titleTextAttributes at your appearance.

appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
Goodbye answered 3/7, 2023 at 11:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.