Skip to content

Instantly share code, notes, and snippets.

@dmsl1805
Last active April 21, 2017 06:16
Show Gist options
  • Save dmsl1805/028451488aa2d194c46b215befc046e5 to your computer and use it in GitHub Desktop.
Save dmsl1805/028451488aa2d194c46b215befc046e5 to your computer and use it in GitHub Desktop.
ContainerViewController
//
// 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