Unwind segue from navigation back button in Swift

后端 未结 4 934
无人及你
无人及你 2020-12-14 19:15

I have a settings screen, in that I have a table cell. By clicking on that I take to another screen where user can choose an option and I want it back in the previous view c

4条回答
  •  盖世英雄少女心
    2020-12-14 19:38

    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.

提交回复
热议问题