Skip to content

Instantly share code, notes, and snippets.

@asowers1
Last active October 24, 2018 22:35
Show Gist options
  • Save asowers1/6054f5661477419443804cf1db27b22b to your computer and use it in GitHub Desktop.
Save asowers1/6054f5661477419443804cf1db27b22b to your computer and use it in GitHub Desktop.
Lazy Loading view controllers in Swift
/**
* Lazy load view controller example
*/
class MainViewController: UIViewController {
lazy var firstViewController: FirstViewController = {
return self.storyboard!.instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController
}()
lazy var secondViewController: SecondViewController = {
return self.storyboard!.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
}()
@IBOutlet weak var promptContainerView: UIView
var visiblePrompt: UIViewController?
func viewWillAppear(animated: Bool) {
let foo = true
if foo { // if some condition is true
self.presentPrompt(self.firstViewController)
} else {
self.presentPrompt(self.secondViewController)
}
}
// add our lazily loaded view controller to the container outlet and match the container constraints.
// Also, you can optionally throw in a view animation
func presentPrompt(viewController: UIViewController, animate: ((UIView?, UIView, () -> Void) -> Void) = { _, _, block in block() }){
self.visiblePrompt?.willMoveToParentViewController(nil)
self.addChildViewController(viewController)
viewController.hostViewController = self
let contentView = viewController.view
let containerView = self.promptContainerView
containerView.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: contentView, attribute: .Top, relatedBy: .Equal, toItem: containerView, attribute: .Top, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: contentView, attribute: .Bottom, relatedBy: .Equal, toItem: containerView, attribute: .Bottom, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: contentView, attribute: .Leading, relatedBy: .Equal, toItem: containerView, attribute: .Leading, multiplier: 1.0, constant: 0.0),
NSLayoutConstraint(item: contentView, attribute: .Trailing, relatedBy: .Equal, toItem: containerView, attribute: .Trailing, multiplier: 1.0, constant: 0.0),
])
animate(self.visiblePrompt?.view, viewController.view) {
self.visiblePrompt?.view.removeFromSuperview()
self.visiblePrompt?.removeFromParentViewController()
viewController.didMoveToParentViewController(self)
self.visiblePrompt = viewController
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment