【问题标题】:How to go back to previous view in Objective-C?如何返回到 Objective-C 中的先前视图?
【发布时间】:2012-07-09 09:43:48
【问题描述】:

我是iOS编程的初学者,我想实现返回主页视图的功能。

我已经使用了这个代码:

-(IBAction)onclickhome:(id)sender
{

    [self.navigationController popViewControllerAnimated:YES];
}

我在主页按钮点击事件中使用了navigationController,但它没有跳转到主屏幕。

您有任何适用于我的代码的建议和源代码吗?

【问题讨论】:

    标签: objective-c ios uinavigationcontroller


    【解决方案1】:

    我不确定我是否理解你的问题。

    你是什么意思

    我在主页按钮单击事件中使用了 navigationController 但它是 不跳转到主屏幕

    ?

    如果你想弹出到根控制器,你可以使用popToRootViewControllerAnimated

    [self.navigationController popToRootViewControllerAnimated:YES];
    

    来自UINavigationController 的 Apple 文档

    popToRootViewControllerAnimated:
    
    Pops all the view controllers on the stack except the root view controller and updates the display.
    - (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
    

    如果你设置了UINavigationController 并且它的根控制器被称为 A,那么如果你从 A 导航到 B,然后从 B 导航到 C,你有两种可能返回到以前的控制器(你可以有其他但我列出了主要的):

    • 使用popViewControllerAnimated 从 C 导航回 B
    • 使用popToRootViewControllerAnimated 从 C 导航回 A

    【讨论】:

    • 使用你的例子,我怎么能从 D -> B 跳回来?视图的变化也应该通过翻转动画来完成。有什么想法吗?
    • @taymless popToViewController 是选择。有关参考,请参阅developer.apple.com/library/ios/#documentation/uikit/reference/…
    • 是的,我看到了,但是我要如何定义它是翻转动画呢?我会尝试transitionFromViewController:toViewController:duration:options:animations:completion:,因为它允许设置动画类型,即UIViewAnimationOptionTransitionFlipFromRight
    • @taymless 获得支持的最佳方式是为其打开一个新问题。我还没有尝试过,我不知道如何帮助你。对不起。
    • 好的。如果有人感兴趣:stackoverflow.com/questions/12384493/…
    【解决方案2】:

    来回导航视图的最佳方法是从导航视图控制器堆栈中推送和弹出视图。

    要返回一个视图,请使用以下代码。这将确保保持视图之间的平滑过渡。

    UINavigationController *navigationController = self.navigationController;
    [navigationController popViewControllerAnimated:YES];
    

    要返回两个视图,请执行以下操作

    UINavigationController *navigationController = self.navigationController;
    [navigationController popViewControllerAnimated:NO];
    [navigationController popViewControllerAnimated:YES];
    

    如果您没有返回到预期的视图,请在弹出任何视图之前执行以下代码...

    UINavigationController *navigationController = self.navigationController;
    NSLog(@"Views in hierarchy: %@", [navigationController viewControllers]);
    

    您应该会看到如下所示的数组,这将帮助您验证堆栈是否按预期维护。

    Views in hierarchy: (
        "<Main_ViewController: 0x1769a3b0>",
        "<First_ViewController: 0x176a5610>",
        "<Second_ViewController: 0x176af180>"
    

    【讨论】:

      【解决方案3】:

      我用

      [self dismissViewControllerAnimated:YES completion:nil];
      

      因为其他答案在 Xcode 8.0 中不起作用

      【讨论】:

        猜你喜欢
        • 2020-04-27
        • 1970-01-01
        • 2017-11-09
        • 2012-11-07
        • 1970-01-01
        • 2014-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多