Skip to content

Instantly share code, notes, and snippets.

@ksm
Last active June 14, 2018 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksm/72e2d0a3f2153569c36a7a7693479f8b to your computer and use it in GitHub Desktop.
Save ksm/72e2d0a3f2153569c36a7a7693479f8b to your computer and use it in GitHub Desktop.
Lets a view controller embed a child view controller.
import UIKit
protocol Embedding: class {
var embeddedViewController: UIViewController? { get set }
}
enum EmbeddingAnimation {
case none
case flipFromLeft
case crossDissolve
func animationOption() -> UIViewAnimationOptions {
switch self {
case .none:
return []
case .flipFromLeft:
return .transitionFlipFromLeft
case .crossDissolve:
return .transitionCrossDissolve
}
}
func duration() -> TimeInterval {
switch self {
case .none:
return 0
case .flipFromLeft:
return 0.75
case .crossDissolve:
return 0.3
}
}
}
extension Embedding {
func embedViewController(_ viewController: UIViewController, animation: EmbeddingAnimation) {
func embed() {
let s = self as! UIViewController
if let viewControllerForRemoval = self.embeddedViewController {
viewControllerForRemoval.willMove(toParentViewController: nil)
viewControllerForRemoval.view.removeFromSuperview()
viewControllerForRemoval.removeFromParentViewController()
}
self.embeddedViewController = viewController
s.addChildViewController(viewController)
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
s.view.addSubview(viewController.view)
viewController.didMove(toParentViewController: s)
}
switch animation {
case .none:
embed()
default:
let s = self as! UIViewController
UIView.transition(with: s.view, duration: animation.duration(), options: animation.animationOption(), animations: embed, completion: nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment