Skip to content

Instantly share code, notes, and snippets.

@plivesey
Last active February 5, 2020 18:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plivesey/76a8c76217f83ae0bc26f428740afeb8 to your computer and use it in GitHub Desktop.
Save plivesey/76a8c76217f83ae0bc26f428740afeb8 to your computer and use it in GitHub Desktop.
public class RootViewController<Content: View>: UIHostingController<Content> {
public init(view: Content, rootViewManager: RootViewManager) {
super.init(rootView: view)
rootViewManager.rootViewController = self
}
@objc required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension RootViewController where Content: HostableView {
public convenience init(view: Content) {
self.init(view: view, rootViewManager: view.rootViewManager)
}
}
public class RootViewManager: NSObject {
weak var rootViewController: UIViewController?
public var isDismissEnabled: Bool {
get {
!(rootViewController?.isModalInPresentation ?? false)
}
set {
rootViewController?.isModalInPresentation = !newValue
}
}
public func showModal<Content: HostableView>(_ view: Content,
completion: @escaping () -> Void = {}) {
let modalViewController = RootViewController(view: view)
rootViewController?.present(modalViewController, animated: true, completion: completion)
}
public func showModal<Content: View>(_ view: Content,
rootViewManager: RootViewManager,
completion: @escaping () -> Void = {}) {
let modalViewController = RootViewController(view: view, rootViewManager: rootViewManager)
rootViewController?.present(modalViewController, animated: true, completion: completion)
}
}
public protocol HostableView: View {
var rootViewManager: RootViewManager { get }
}
struct RootView: View, HostableView {
@ObservedObject var rootViewManager = RootViewManager() // This is passed down as an environment object to all relevant children
var body: some View { ... }
private func buttonTapped() {
self.rootViewManager.showModal(SomeView())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment