Skip to content

Instantly share code, notes, and snippets.

@ksm
Last active Jun 14, 2018
Embed
What would you like to do?
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