Last active
February 5, 2020 18:08
-
-
Save plivesey/76a8c76217f83ae0bc26f428740afeb8 to your computer and use it in GitHub Desktop.
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
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