简体   繁体   中英

How to access UINavigationController from a UIViewController

In my AppDelegate I have the following code:

UIViewController *viewController1 = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
UINavigationController *itemsNavigationController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];

How can I set the UIVNagigationBar's background color to green?

If I do:

[self.navigationController.navigationBar setTintColor:[UIColor greenColor]];

from the viewController1, this has no effect.

Thanks in advance!

UPDATE:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"MyTitle", @"");

        [self.navigationController.navigationBar setTintColor:[UIColor greenColor]];
        [self.parentViewController.navigationController.navigationBar setTintColor:[UIColor greenColor]];
    }
    return self;
}

Both have no effects

In the initWithNibName:bundle method your view controller can't yet have a navigation controller.

If your navigation controller is created from a nib file too, try implementing the awakeFromNib method of UIViewController and set the color there. awakeFromNib is called once every object on the nib file has been loaded and initialized.

If you create the navigation controller programmatically, then you should set the color only after adding the view controller (loaded from the nib) to your navigation controller. You can either do this where you add the view controller. Or try implementing the viewDidLoad or viewWillAppear methods of UIViewController to set the color.

You're doing it too soon. (You're not getting an error, but your messages are fruitless messages sent to nil , as you can easily discover by using NSLog.) Wait until FirstViewController's viewDidLoad .

Or use the appearance proxy as already suggested. The advantage here is partly that timing becomes unimportant; you can do it in advance, before any view controller instances even exist. Example:

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/ch19p549navigationInterface/p471p482navigationInterface/AppDelegate.m

You can also use the appearance method in iOS 5 to change tints for your navigation bars across the app. For example, in your application:didFinishLaunchingWithOptions you can:

if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) 
{
    [[UINavigationBar appearance] setTintColor:[UIColor greenColor]];
}

尝试[itemsNavigationController1.navigationBar setTintColor:[UIColor greenColor]];

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