Perform storyboard segues with closures, in Swift
With
SegueManagerit's easy to programatically perform segues and update the destination view controller. The following example demonstrates how to perform a segue and set a view model:
segueManager.performSegue(withIdentifier: "showDetails") { (details: DetailsViewController) in details.viewModel = DetailsViewModel("This is the details view model") }
See the full iOS example, or read below for usage instructions.
A major design goal of SegueManager 2.0 is to allow completely statically typed segues using
R.swift.
With R.swift the above example becomes:
self.performSegue(withIdentifier: R.segue.masterViewController.showDetails) { segue in segue.destination.viewModel = DetailsViewModel("This is the details view model") }
Here the
segueparameter is of type:
TypedStoryboardSegueInfo, which means the
.destinationfield is of the correct type.
To use R.swift together with SegueManager, include this subspec to your Podfile:
pod 'SegueManager/R.swift'
SegueManager is available for both iOS and OS X. Using CocoaPods, SegueManager can be integrated into your Xcode project by specifying it in your
Podfile:
pod 'SegueManager'
Then, run the following command:
$ pod install
There are two methods of using SegueManager:
SegueManagerViewController,
SegueManagerTableViewController,
SegueManagerCollectionViewController, etc.
Or, if you don't want to rely on inheritance (often problematic), create a SegueManager yourself:
SegueManager, instantiated with
self.
SeguePerformerprotocol
prepare(for:)and call SegueManager.
import SegueManagerclass MasterViewController: UIViewController, SeguePerformer {
lazy var segueManager: SegueManager = { // SegueManager based on the current view controller return SegueManager(viewController: self) }()
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { segueManager.prepare(for: segue) } }
After this setup, simply call
performSegueon self and pass it a handler.
Call
performSegue(withIdentifier)with a string identifier and pass a handler. Make sure you specify the type of the destination ViewController, since that can not be inferred:
self.performSegue(withIdentifier: "showDetails") { (details: DetailsViewController) in details.viewModel = DetailsViewModel("This is the details view model") }
Call
performSegue(withIdentifier)with a segue identifier from
R.segue.*and pass a handler.
self.performSegue(withIdentifier: R.segue.masterViewController.showDetails) { segue in segue.destination.viewModel = DetailsViewModel("This is the details view model") }
The handler will be called after the destination view controller has been instantiated, but before its view has been loaded or any animations start.
SegueManagerViewControlleras
UIViewControllersubclass
UINavigationControllerin destination
SegueManager is written by Tom Lokhorst of Q42 and available under the MIT license, so feel free to use it in commercial and non-commercial projects.