是否可以为单击事件调用PopViewControllerAnimated和PushViewController

时间:2011-12-13 05:14:48

标签: objective-c xcode

在按钮点击操作中,我想要同时销毁当前屏幕,我想将其导航到主屏幕而不是之前的屏幕。 我尝试通过放置此代码来做到这一点,但没有用。

-(IBAction)     sel_goback
{
    [self.navigationController popViewControllerAnimated:YES];
    Home1ViewController *HM = [[Home1ViewController alloc] initWithNibName:@"Home1ViewController" bundle:nil];
    [self.navigationController pushViewController:HM animated:YES];
    [HM release];

}

1 个答案:

答案 0 :(得分:1)

如果self是顶级视图控制器,则在popViewControllerAnimated:返回时,self.navigationController已设置为nil。试试这个:

-(IBAction)     sel_goback
{
    UINavigationController *nav = self.navigationController;
    [nav popViewControllerAnimated:YES];
    Home1ViewController *HM = [[Home1ViewController alloc] initWithNibName:@"Home1ViewController" bundle:nil];
    [nav pushViewController:HM animated:YES];
    [HM release];

}

然而,“主屏幕”听起来像是已经存在于导航控制器堆栈中的东西。也许你真正想要的是这样的:

-(IBAction)     sel_goback
{
    UINavigationController *nav = [self.navigationController];
    while (nav.viewControllers.count > 1 && ![nav.topViewController isKindOfClass:[Home1ViewController class]])
        [nav popViewControllerAnimated:YES];

    if (![nav.topViewController isKindOfClass:[Home1ViewController class]]) {
        Home1ViewController *home = [[Home1ViewController alloc] initWithNibName:@"Home1ViewController" bundle:nil];
        [nav setViewControllers:[NSArray arrayWithObject:home] animated:YES];
    }
}