Unwind segue from navigation back button in Swift

帅比萌擦擦* 提交于 2019-11-28 21:23:40
Big Red

Here's my solution, based on Objective-C code from Blankarsch to this StackOverflow question: How to trap the back button event

Put this code inside the View Controller you want to trap the Back button call from:

override func didMoveToParentViewController(parent: UIViewController?) {
    if (!(parent?.isEqual(self.parentViewController) ?? false)) {
        println("Back Button Pressed!")
    }
}

Inside of the if block, handle whatever you need to pass back. You'll also need to have a reference back to calling view controller as at this point most likely both parent and self.parentViewController are nil, so you can't navigate the View Controller tree.

Also, you might be able to get away with simply checking parent for nil as I haven't found a case where pressing the back button didn't result in parent being nil. So something like this is a bit more concise:

override func didMoveToParentViewController(parent: UIViewController?) {
    if (parent == nil) {
        println("Back Button Pressed!")
    }
}

But I can't guarantee that will work every time.

Andrew

John R Perry

Do the following in the view controller that has the back button

Swift 3

override func didMove(toParentViewController parent: UIViewController?) {
    if !(parent?.isEqual(self.parent) ?? false) {
        print("Parent view loaded")
    }
    super.didMove(toParentViewController: parent)
}

I tried the same and it seems that you cannot catch the standard back button's action so the solution will be to use a custom button and bind it to a segue which leads back to the previous page.

You could use some sort of delegation as you did or use a custom back button and an unwind segue.

Better even, you could handle passing data between your view controllers using a mediator:

http://cocoapatterns.com/passing-data-between-view-controllers/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!