Last active
April 21, 2017 06:16
-
-
Save dmsl1805/028451488aa2d194c46b215befc046e5 to your computer and use it in GitHub Desktop.
ContainerViewController
This file contains 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
// | |
// ContainerViewController.swift | |
// | |
// Created by Dmitriy Shulzhenko on 1/15/17. | |
// Copyright © 2017 Dmitriy Shulzhenko. All rights reserved. | |
// | |
import UIKit | |
class ContainerViewController: UIViewController { | |
public weak var currentViewController: UIViewController? | |
private var transitionCompleted: Bool = true | |
private var frameForChild: CGRect { | |
return CGRect(origin: CGPoint.zero, size: view.frame.size) | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
if let current = currentViewController { | |
addChildViewController(current) | |
current.view.frame = frameForChild | |
view.addSubview(current.view) | |
current.didMove(toParentViewController: self) | |
} | |
} | |
public func show(_ vc: UIViewController, | |
duration: TimeInterval = 0, | |
options: UIViewAnimationOptions = .transitionCrossDissolve, | |
animations: (() -> Void)? = nil, | |
completion: (() -> Void)? = nil) { | |
guard transitionCompleted else { return } | |
guard vc != currentViewController else { return } | |
guard let currentViewController = self.currentViewController else { return } | |
transitionCompleted = false | |
currentViewController.willMove(toParentViewController: nil) | |
addChildViewController(vc) | |
vc.view.frame = frameForChild | |
transition(from: currentViewController, | |
to: vc, | |
duration: duration, | |
options: options, | |
animations: animations) { [unowned self] finished in | |
currentViewController.removeFromParentViewController() | |
vc.didMove(toParentViewController: self) | |
self.currentViewController = vc | |
self.transitionCompleted = true | |
completion?() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment