检测导航栏上按下“后退”按钮的时间 [英] Detecting when the 'back' button is pressed on a navbar

查看:107
本文介绍了检测导航栏上按下“后退”按钮的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在导航栏上按下后退按钮(返回上一屏幕,返回父视图)按钮时,我需要执行一些操作。

I need to perform some actions when the back button(return to previous screen, return to parent-view) button is pressed on a Navbar.

是否有一些方法我可以实现捕获事件并触发一些动作,以便在屏幕消失之前暂停和保存数据?

Is there some method I can implement to catch the event and fire off some actions to pause and save data before the screen disappears?

推荐答案

更新:根据一些评论,原始答案中的解决方案在iOS 8+的某些情况下似乎不起作用。我无法在没有进一步细节的情况下验证实际情况。

UPDATE: According to some comments, the solution in the original answer does not seem to work under certain scenarios in iOS 8+. I can't verify that that is actually the case without further details.

对于那些人而言,在那种情况下还有另一种选择。通过覆盖 willMove(toParentViewController:),可以检测何时弹出视图控制器。基本的想法是当 nil 时,正在弹出视图控制器。

For those of you however in that situation there's an alternative. Detecting when a view controller is being popped is possible by overriding willMove(toParentViewController:). The basic idea is that a view controller is being popped when parent is nil.

查看实施容器视图控制器 了解更多详情。

自iOS 5以来,我发现处理这种情况的最简单方法正在使用新方法 - (BOOL)isMovingFromParentViewController

Since iOS 5 I've found that the easiest way of dealing with this situation is using the new method - (BOOL)isMovingFromParentViewController:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if (self.isMovingFromParentViewController) {
    // Do your stuff here
  }
}

- (BOOL)isMovingFromParentViewController 在推送和弹出导航堆栈中的控制器时有意义。

- (BOOL)isMovingFromParentViewController makes sense when you are pushing and popping controllers in a navigation stack.

但是,如果你要呈现模态视图控制器,你应该使用 - (BOOL)isBeingDismissed 代替:

However, if you are presenting modal view controllers you should use - (BOOL)isBeingDismissed instead:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if (self.isBeingDismissed) {
    // Do your stuff here
  }
}

此问题所述,您可以合并这两个属性:

As noted in this question, you could combine both properties:

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];

  if (self.isMovingFromParentViewController || self.isBeingDismissed) {
    // Do your stuff here
  }
}

其他解决方案依赖于 UINavigationBar 的存在。我更喜欢这种方法,因为它从触发事件的动作中解除了执行所需的任务,即按下后退按钮。

Other solutions rely on the existence of a UINavigationBar. I like this approach more because it decouples the required tasks to perform from the action that triggered the event, i.e. pressing a back button.

这篇关于检测导航栏上按下“后退”按钮的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆