当新控制器被推送到UINavigationController堆栈时,UINavigationBar -pushNavigationItem从未被调用

时间:2011-09-09 02:09:04

标签: ios

今晚我正在做一些测试来查看原生UINavigationBar的行为。我创建了一个简单的代码片段,它执行以下操作:

- (void)pushController {
    PHViewController *ctrl2 = [[[PHViewController alloc] initWithNibName:@"PHViewController" bundle:nil] autorelease];
    ctrl2.shouldShowPrompt = YES;
    [self.viewController pushViewController:ctrl2 animated:YES];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    PHViewController *ctrl = [[[PHViewController alloc] initWithNibName:@"PHViewController" bundle:nil] autorelease];
    ctrl.shouldShowPrompt = YES;
    ctrl.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Push" 
                                                                           style:UIBarButtonItemStyleDone
                                                                          target:self
                                                                          action:@selector(pushController)] autorelease];

    self.viewController = [[[PHNavigationController alloc] initWithRootViewController:ctrl] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

现在我已经将UINavigationBar的{​​{1}}分类(我知道这是非法的,这是一个教育问题),我已经克服了以下方法:

UINavigationController

这是我的问题:为什么控制台中存在“弹出导航项”(因此被调用的方法)和“推送导航项”不是?

2 个答案:

答案 0 :(得分:11)

我找到了原因:它调用 - (void)pushNavigationItem:(UINavigation *)项不调用 - (void)pushNavigationItem:animated!

无论如何,谢谢!

答案 1 :(得分:1)

对于那些像我一样苦苦挣扎的人来说,这是一个解决方案。在使用自定义UINavigationController的自定义UINavigationBar子类中,使用以下代码覆盖pushViewController方法:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [super setViewControllers:[self.viewControllers arrayByAddingObject:viewController]
                     animated:animated];
}

然后在您的自定义UINavigationBar子类中,您可以自定义navigationItems,如下所示:

- (void)pushNavigationItem:(UINavigationItem *)item animated:(BOOL)animated
{
    // customize your navigationItem here...

    [super pushNavigationItem:item animated:animated];
}