3

在我的 AppDelegate 我有以下代码:

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

如何将 UIVNagigationBar 的背景颜色设置为绿色?

如果我做:

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

从 viewController1 来看,这没有效果。

提前致谢!

更新:

- (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;
}

两者都没有影响

4

4 回答 4

5

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.

于 2012-09-19T18:11:25.477 回答
3

你做得太快了。(您没有收到错误消息,但您的消息是发送到的无果消息nil,您可以通过使用 NSLog 轻松发现。)等到 FirstViewController 的viewDidLoad.

或者使用已经建议的外观代理。这里的优势部分在于时机变得不重要。您可以在任何视图控制器实例存在之前提前完成。例子:

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

于 2012-09-19T18:31:07.970 回答
2

您还可以使用appearanceiOS 5 中的方法来更改应用程序中导航栏的色调。例如,在你的application:didFinishLaunchingWithOptions你可以:

if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) 
{
    [[UINavigationBar appearance] setTintColor:[UIColor greenColor]];
}
于 2012-09-19T18:23:49.387 回答
0

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

于 2012-09-19T17:58:42.910 回答