Reputation: 461
I need to call a function when I press the back button. Preferably, without having to create another button
Upvotes: 5
Views: 2795
Reputation: 36610
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).
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.
Upvotes: 10
Reputation: 535138
Implement viewWillDisappear
and, in it, test isMovingFromParentViewController
. If the latter is true, you're being popped.
Upvotes: 6