Skip to content

Instantly share code, notes, and snippets.

@MohamedKari
Created January 23, 2021 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MohamedKari/fc517270f2c4e3b323a1cba3ba3ee707 to your computer and use it in GitHub Desktop.
Save MohamedKari/fc517270f2c4e3b323a1cba3ba3ee707 to your computer and use it in GitHub Desktop.
UIKit to SwiftUI Delegation with Coordinators and ViewControllers

Preliminaries

  1. 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
  2. Create struct with name CloudVisionViewController inheriting from UIViewControllerRepresentable which covers the missing link between SwiftUI and UIKit
  3. 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)
}
  1. Implement this CloudVisionDelegate in the Coordiantor class in the CloudVisionViewController
  2. Assign the coordinator as delegate to the newly instaniated UICloudVisionViewController in the makeUIViewController func
uiCloudVisionViewController.delegate = context.coordinator
  1. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment