Created
March 31, 2020 16:54
-
-
Save badrinathvm/aa88ec0b66b99d4acb85f7069ae40625 to your computer and use it in GitHub Desktop.
Wrapper for embedding UIViewController in SwiftUI app.
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
//MARK:- Packs the UIKit's ViewController in SwiftUI View. | |
public struct Pack<Packed: UIViewController> : UIViewControllerRepresentable { | |
public typealias Updater = (Packed, Context) -> Void | |
//two closures for each of the method requirement of UIViewControllerRepresentable | |
public var makeViewController: () -> Packed | |
public var updateViewController: Updater | |
//autoclosure here creates the viewcontrollers lazily, @escaping to preserve the closure to execute asynchronously | |
init(_ makeViewController: @escaping @autoclosure () -> Packed, updateViewController: @escaping Updater) { | |
self.makeViewController = makeViewController | |
self.updateViewController = updateViewController | |
} | |
public func makeUIViewController(context: Context) -> Packed { | |
return makeViewController() | |
} | |
public func updateUIViewController(_ uiViewController: Packed, context: Context) { | |
updateViewController(uiViewController, context) | |
} | |
} | |
//MARK:- convinence initilazers | |
extension Pack { | |
// only viewController as argument. | |
public init(_ makeViewController: @escaping @autoclosure () -> Packed) { | |
self.makeViewController = makeViewController | |
self.updateViewController = { _ , _ in } | |
} | |
// viewcontroller without context as argument. | |
public init(_ makeViewController: @escaping @autoclosure () -> Packed , updateViewController: @escaping (Packed) -> Void ) { | |
self.makeViewController = makeViewController | |
self.updateViewController = { viewController, _ in updateViewController(viewController) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment