检测何时按下导航栏上的“后退"按钮 [英] Detecting when the 'back' button is pressed on a navbar
问题描述
当导航栏上的后退按钮(返回上一屏幕,返回父视图)按钮被按下时,我需要执行一些操作.
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?
推荐答案
UPDATE: 根据一些评论,原始答案中的解决方案在 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:)
可以检测何时弹出视图控制器.基本思想是当 parent
为 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
. Instead like my approach more because it decouples the required tasks to perform from the action that triggered the event, i.e. pressing a back button.
这篇关于检测何时按下导航栏上的“后退"按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!