Preliminaries
- Create
final class
with name UICloudVisionViewController inheriting UIViewController with all the typical (the UI in the name refers to UIKit) which follows the UIKit approach - Create
struct
with name CloudVisionViewController inheriting from UIViewControllerRepresentable which covers the missing link between SwiftUI and UIKit - To exchange data between UIKit and SwiftUI, add a coordinator class to CloudVisionViewController and return an instance of it in the makeCoordinator func
Reflect changes from UIKit in SwiftUI: Communication is delegate-based. The goal is to call a delegate in the custom UIKit UICloudVisionViewController which updates the parent SwiftUI view
4. Add the changing variable to the SwiftUI ContentView as a state variable: @State private var mostRecentFrame: UIImage? = nil
5. Add the changing variable to the CloudVisionViewController as a @Binding var mostRecentFrame: UIImage?
6. Implement a CloudVisionDelegate protocol and in there a function with a Signature such as didUpdateMostRecentFrame(uiCloudVisionViewController: UICloudVisionViewController, mostRecentFrame: UIImage)
7. Add this CloudVisionDelegate as a variable in your custom UICloudVisionViewController (var delegate: UICloudVisionViewControllerDelegate?
) will invoked from within the the UI...ViewController:
if let delegate = delegate {
delegate.didUpdateMostRecentFrame(uiCloudVisionViewController: self, mostRecentFrame: image)
}
- Implement this CloudVisionDelegate in the Coordiantor class in the CloudVisionViewController
- Assign the coordinator as delegate to the newly instaniated UICloudVisionViewController in the makeUIViewController func
uiCloudVisionViewController.delegate = context.coordinator
- In the delegated method in the Coordinator class, update the @Binding variable in the UICloudVisionViewController by accessing the
parent
.
Reflect changes from SwiftUI in UIKit