[英]How can I call a function when the navigation back button is pressed?
I need to call a function when I press the back button. 当我按下后退按钮时,我需要调用一个函数。 Preferably, without having to create another button
优选地,不必创建另一个按钮
Place the following in your view controller. 将以下内容放在视图控制器中。
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if parent == nil {
// The view is being removed from the stack, so call your function here
}
}
When parent is nil, it means the view is being removed from the stack (ie the back button was pressed). 当parent为nil时,表示视图正从堆栈中删除(即按下后退按钮)。
One consideration when compared with matt's answer is that willMove
is called before viewWillDisappear
. 与matt的答案相比,一个考虑因素是在
viewWillDisappear
之前调用willMove
。 Your mileage will vary based on what your function does, but this can result in issues based on your specific needs. 您的里程将根据您的功能而有所不同,但这可能会导致根据您的具体需求出现问题。 With that said, either answer is perfectly capable of providing what you requested.
话虽如此,答案完全能够满足您的要求。
Implement viewWillDisappear
and, in it, test isMovingFromParentViewController
. 实现
viewWillDisappear
并在其中测试isMovingFromParentViewController
。 If the latter is true, you're being popped. 如果后者是真的,那么你就会被弹出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.