Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access UINavigationController from a UIViewController

Tags:

ios

iphone

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

like image 507
CyberK Avatar asked Jul 01 '26 07:07

CyberK


1 Answers

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.

like image 133
DrummerB Avatar answered Jul 03 '26 00:07

DrummerB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!