Skip to content

Instantly share code, notes, and snippets.

@mitsuse
Created April 1, 2016 01:12
Show Gist options
  • Save mitsuse/71fa33a59ffdb0ff684a04ff69ae45d1 to your computer and use it in GitHub Desktop.
Save mitsuse/71fa33a59ffdb0ff684a04ff69ae45d1 to your computer and use it in GitHub Desktop.
An implementation of view controller to choose and present a view conditionally.
import UIKit
public protocol ConditionalPresenter: class {
var view: UIView! { get }
func addChildViewController(childController: UIViewController)
var current: UIViewController! { get set }
func generateController() -> UIViewController
}
extension ConditionalPresenter {
public func updateController() {
discardCurrent()
updateCurrent()
}
private func discardCurrent() {
current?.removeFromParentViewController()
current?.view.removeFromSuperview()
current = nil
}
public func updateFrame() {
current.view.frame = view.frame
}
private func updateCurrent() {
current = generateController()
addChildViewController(current)
view.addSubview(current.view)
updateFrame()
}
}
public class ConditionalController: UIViewController, ConditionalPresenter {
public var current: UIViewController!
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateController()
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
updateFrame()
}
public func generateController() -> UIViewController {
fatalError("Not implemented.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment