-->

iOS 7 UINavigationBar appearance not working first

2019-03-24 10:59发布

问题:

I am trying to change the look of the UINavigationBar in my iOS7 app. I am doing the following:

- (void)viewDidLoad
{
    [super viewDidLoad];

    m_sNumberToCall = @"";

    UIBarButtonItem * btn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"IconHome.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(btHomeTouched:)];
    self.navigationItem.leftBarButtonItem = btn;

    self.navigationController.navigationBar.translucent = YES;


    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"TVCNavBack.png"] forBarMetrics:UIBarMetricsDefault];

    NSShadow * shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
    shadow.shadowOffset = CGSizeMake(0, 1);
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0],
                                                           NSForegroundColorAttributeName,
                                                           shadow,
                                                           NSShadowAttributeName,
                                                           [UIFont fontWithName:@"Helvetica-Bold" size:21.0],
                                                           NSFontAttributeName,
                                                           nil]];
}

But, the first time I present the UITableViewController it is the standard iOS7 nav bar, then I press home and present it again and it is my new look.

Any ideas why it does not work the first time?

回答1:

Don't change the appearance but the navigation bar directly. The appearance affects only the future instances but not the already created ones.

Change:

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"TVCNavBack.png"] forBarMetrics:UIBarMetricsDefault];

to:

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"TVCNavBack.png"] forBarMetrics:UIBarMetricsDefault];


回答2:

The answer before only helps you with the background image but not with the title text attributes.

You don't need to change your code but all you have to do is move it to

applicationDidFinishLaunchingWithOptions

in your AppDelegate.m file.