Skip to content

Instantly share code, notes, and snippets.

@dneprDroid
Last active July 13, 2017 19:38
Show Gist options
  • Save dneprDroid/d4ad15f833f49718929a4244548c18f1 to your computer and use it in GitHub Desktop.
Save dneprDroid/d4ad15f833f49718929a4244548c18f1 to your computer and use it in GitHub Desktop.
MainNavigationProtocol.swift
import UIKit
protocol MainNavigationProtocol: class {
var cached:Bool? {get set}
static var storyboardName: String {get}
}
extension MainNavigationProtocol where Self : UIViewController {
static var storyboardName: String {
return "Main"
}
static func cached(from navVC: UINavigationController) -> Self {
for vc in (navVC.viewControllers) {
if vc.isKind(of: Self.self) {
let controller = vc as! Self
controller.cached = true
return controller
}
}
let vcId = String(describing: self)
var vc = instantiateController(fromStoryboard: storyboardName, withIdentifier: vcId) as? Self
if vc == nil {
vc = Self()
}
vc!.cached = false
return vc!
}
private static func instantiateController(fromStoryboard sbName: String, withIdentifier vcName: String) -> UIViewController? {
let sb = UIStoryboard(name: sbName, bundle: nil)
if let obj = sb.value(forKey: "identifierToNibNameMap") as? [String: Any],
obj[vcName] != nil {
return sb.instantiateViewController(withIdentifier: vcName)
}
return nil
}
func start(with navVC: UINavigationController?) {
if let navVC = navVC {
if let cached = cached, cached {
navVC.popToViewController(self, animated: false)
} else {
navVC.pushViewController(self, animated: false)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment