iOS - UINavigationController并添加左栏按钮?

时间:2012-07-16 16:07:47

标签: ios uinavigationcontroller uibarbuttonitem

以下mwthod是UINavigationController的委托方法。我想决定是否将左项添加到每个页面。下面的代码不起作用,我做错了吗?

我不想通过ViewController本身执行此操作。我希望NavigationCopntroller负责这项任务。

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize 
                                                                                  target:self 
                                                                                  action:@selector(menuItemSelected:)];
    [self.navigationItem setLeftBarButtonItem:menuItem];

    // I also tried 
    // [viewController.navigationItem setLeftBarButtonItem:menuItem];
}

2 个答案:

答案 0 :(得分:1)

我认为问题在于你试图访问viewController上的navigationItem属性,但它不存在,因为在willShowViewController方法中viewController还没有在navigationController堆栈中,尝试使用didShowViewController委托方法

像这样:

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize 
                                                                                  target:self 
                                                                                  action:@selector(menuItemSelected:)];
    [self.navigationItem setLeftBarButtonItem:menuItem];

    [viewController.navigationItem setLeftBarButtonItem:menuItem]; 

}

答案 1 :(得分:1)

控制台中有一条警告说“嵌套推送可能会破坏navigationController” 我正在将2个Viewcontroller推入堆栈,而不是一次推送1个viewController。

修复此问题并删除警告也解决了这个问题。