I need to call a function when I press the back button. Preferably, without having to create another button
我按下后退按钮时需要调用一个函数。优选地,不必创建另一个按钮
2 个解决方案
#1
8
Place the following in your view controller.
将以下内容放在视图控制器中。
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: 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
. 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.
与matt的答案相比,一个考虑因素是在viewWillDisappear之前调用willMove。您的里程将根据您的功能而有所不同,但这可能会导致根据您的特定需求出现问题。话虽如此,任何一个答案都能完全满足您的要求。
#2
5
Implement viewWillDisappear
and, in it, test isMovingFromParentViewController
. If the latter is true, you're being popped.
实现viewWillDisappear,并在其中测试isMovingFromParentViewController。如果后者是真的,那么你就会被弹出。
#1
8
Place the following in your view controller.
将以下内容放在视图控制器中。
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: 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
. 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.
与matt的答案相比,一个考虑因素是在viewWillDisappear之前调用willMove。您的里程将根据您的功能而有所不同,但这可能会导致根据您的特定需求出现问题。话虽如此,任何一个答案都能完全满足您的要求。
#2
5
Implement viewWillDisappear
and, in it, test isMovingFromParentViewController
. If the latter is true, you're being popped.
实现viewWillDisappear,并在其中测试isMovingFromParentViewController。如果后者是真的,那么你就会被弹出。