Leo Valentim
Leo Valentim

Reputation: 461

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

Upvotes: 5

Views: 2795

Answers (2)

CodeBender
CodeBender

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

matt
matt

Reputation: 535138

Implement viewWillDisappear and, in it, test isMovingFromParentViewController. If the latter is true, you're being popped.

Upvotes: 6

Related Questions