繁体   English   中英

如何从UIViewController访问UINavigationController

[英]How to access UINavigationController from a UIViewController

在我的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;
}

两者都没有作用

initWithNibName:bundle方法中,您的视图控制器尚不能使用导航控制器。

如果导航控制器也是从nib文件创建的,请尝试实现UIViewController的awakeFromNib方法并在其中设置颜色。 一旦加载并初始化了nib文件上的每个对象, awakeFromNib调用awakeFromNib

如果以编程方式创建导航控制器,则仅应在将视图控制器(从笔尖加载)添加到导航控制器中之后,才设置颜色。 您可以在添加视图控制器的地方执行此操作。 或尝试实现UIViewControllerviewDidLoadviewWillAppear方法来设置颜色。

您做得太早了。 (您没有收到错误,但是您的消息是发送到nil无效消息,因为您可以使用NSLog轻松找到它。)等待FirstViewController的viewDidLoad

或使用已建议的外观代理。 这里的优势部分是时间变得无关紧要。 您可以在任何视图控制器实例还不存在之前就提前完成。 例:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM