Swift: Function Called when Back is pressed

override func viewWillDisappear(animated: Bool) {
// Do Your Lines of Code ... 
}

Everytime when back button or Done is pressed or a view is popped out this function is called.. you need to override this..


Try this (copied and pasted from manecosta)

Replacing the button to a custom one as suggested on another answer is possibly not a great idea as you will lose the default behavior and style.

One other option you have is to implement the viewWillDisappear method on the View Controller and check for a property named isMovingFromParentViewController. If that property is true, it means the View Controller is disappearing because it's being removed (popped).

Should look something like:

override func viewWillDisappear(animated : Bool) {
    super.viewWillDisappear(animated)

    if (self.isMovingFromParentViewController()){
        // Your code...
    }
}

Here is the link to the other question


Try this:

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // Back button Event handler
    }
}

Tags:

Swift