How to pass data from SwiftUI to uikit

Generated on 8/8/2024

1 search

To pass data from SwiftUI to UIKit, you can use the interoperability features provided by SwiftUI. Here are the steps and relevant details:

  1. Using UIViewRepresentable: This protocol allows you to create and update a UIKit view from SwiftUI. You can pass data from SwiftUI to UIKit by updating the properties of the UIViewRepresentable struct.

  2. Using UIViewControllerRepresentable: Similar to UIViewRepresentable, this protocol is used for view controllers. You can pass data to the UIKit view controller by updating the properties of the UIViewControllerRepresentable struct.

  3. Embedding SwiftUI in UIKit: You can use UIHostingController to embed a SwiftUI view in a UIKit view hierarchy. This allows you to pass data from SwiftUI to UIKit by setting the root view of the UIHostingController.

Here are some relevant segments from the WWDC sessions:

  • SwiftUI essentials:

    • "If there's a view or view controller from UIKit or AppKit that you want to use in SwiftUI, you can create a view representable. This is a special SwiftUI view protocol for creating and updating an associated UIKit or AppKit view using imperative code." SwiftUI essentials (21:25)
    • "The inverse is true as well. If you want to embed a SwiftUI view into a UIKit or AppKit view hierarchy, you can use classes such as HostingViewController. This is created with a root SwiftUI view and can be added to your UIKit or AppKit view controller hierarchy." SwiftUI essentials (20:31)
  • What’s new in UIKit:

    • "In iOS 18, you can now add your existing UIKit gesture recognizers directly to SwiftUI hierarchies by using the new UIJs recognizer representable protocol." What’s new in UIKit (04:22)
  • Enhance your UI animations and transitions:

For more detailed information, you can refer to the sessions mentioned above.