One of the most used patterns in iOS programming are passing data from an initial view controller to a target view controller and the inverse pattern. Hence this post.

Forward segues

In the initial controller, you need to define the action before the segue is taken:

brush: swift
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "NameOfSegue" {
        if let destinationViewController = segue.destinationViewController as? DestinationViewController {
            destinationViewController.parameter = whatever
        }
    }
}

The segue indentifier is defined in Interface Builder. The code above passes whatever argument to the destinationViewController. The destination gets all the data already initialized before the viewDidLoad function.

You never call prepareForSegue directly. It’s a message from UIKit to let you know that a segue has just been triggered.

We can define what is passed as the sender when we perform the segue programatically:

brush: swift
@IBAction func tappedButton(sender: AnyObject) {
    performSegueWithIdentifier("NameOfSegue", sender: UIColor.blueColor())
}

Unwind segues

Unwind segues are used to pop view controllers from the stack. a function must be defined in the destination controller and marked as an IBAction.

brush: swift
@IBAction func detailViewClosed(segue:UIStoryboardSegue) {
  if let detailsViewController = segue.sourceViewController as? DetailViewController {
    self.name = detailsViewController.name
  }
}

Information can be prepared in the source controller with the prepareForSegue function, as in the forward segue case.

UIKit uses the function canPerformUnwindSegueAction to determine how low in the view stack it has to go:

brush: swift
override func canPerformUnwindSegueAction(action: Selector, fromViewController: UIViewController, withSender sender: AnyObject) -> Bool {
  if (self.respondsToSelector(action)) {
    return self.unwindHere;
  }
  return false;
}

Comment