Last active
June 14, 2018 18:30
-
-
Save ksm/72e2d0a3f2153569c36a7a7693479f8b to your computer and use it in GitHub Desktop.
Lets a view controller embed a child view controller.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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