Search code examples
iosswiftuiviewcontrollerviewwillappear

How can I check if my UIViewController got viewed when it appears to the user in my Swift app?


I have a UIViewController with a button. This button has a segue connected to another UIViewController and the segue is of type Show. It looks somehow like this:

self.performSegueWithIdentifier("myIdentifier", sender: user)

and the function prepareForSegue is:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "myIdentifier"){

        if let frD = segue.destinationViewController as? MyNextClass,
        ...

Now when user presses the button, the new UIViewController pops out on fullscreen. It also has a button called exitButton that does one thing:

@IBAction func exitbuttonaction(sender: AnyObject) {

    self.dismissViewControllerAnimated(true, completion: nil)
}

When user presses it - they dismiss this view controller and they see the previous one. That previous container has a viewWillAppear function, but it doesn't get called each time user comes back to it from the 2nd controller. Why not, since it appears every time to the user?

Also, is there any other way of distinguishing when the parent controller appeared to the user? (maybe some other function similar to viewWillAppear that would work while dismissing the 2nd controller)


Solution

  • You must use an UnwindSegue. An UnwindSegue gives you a way to “unwind” the navigation stack and specify a destination to go back to. Your viewWillAppear never call again because already appeared.

    If you want to know what a UnwindSegue is, you can check this answer: stackoverflow anser

    If you want to know how to do it, I recommend these links:

    apple documentation about unwind segues

    tutorial about unwind segues

    youtube videotutorial