6

I have tried integrating a custom UIViewController inside a Swift application but I could not integrate it with SwiftUI elements like Text(). I get this error: Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type. Should I rather use UIView instead of UIViewController?

3
  • 1
    The session you should have already checked out is called Session 231: Integrating SwiftUI. Please, show that you've actually tried to learn (or at the very least, searched here and/or online) this! developer.apple.com/videos/play/wwdc2019/231 Commented Jun 18, 2019 at 18:15
  • 1
    Sorry for sounding snarky - my comment stays. But it is a paradigm change, I understand. So in the interests of being more constructive - watch the link I gave you, paying attention to everything but most of all one thing - even a UIViewController in SwiftUI is actually just a View. Or rather, it's root view is. I've successfully been using an MTKView, wrapped inside a view controller, as a Swift UI View - using delegates and accessing functions in it. But understand, the paradigm change means you need to learn Combine along with SwiftUI. There's about 6 WWDC sessions on this. Commented Jun 18, 2019 at 18:23
  • Ok, thank you! I’ve just watched it. Helped me out. Commented Jun 18, 2019 at 19:24

1 Answer 1

10

UIView’s and UIViewController’s can be implemented in SwiftUI via their respective classes, UIViewRepresentable and UIViewControllerRepresentable.

Apple’s SwiftUI tutorials go over this, and other ways to go about integrating UIKit into SwiftUI.

SwiftUI Tutorials: https://developer.apple.com/tutorials/swiftui/tutorials

Placing a UIView into SwiftUI using UIViewRepresentable: https://developer.apple.com/tutorials/swiftui/creating-and-combining-views ^ see section 5, which uses MKMapView as the UIView

Interfacing with UIKit: https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit

Sorry for the lack of code in my answer, I’m AFK right now. However, the best way to learn is to track down and figure things out yourself. Hope this helps!

Update

If you want to integrate SwiftUI into an existing UIKit application, look into using UIHostingController. It works like:

UIHostingController(rootView: MySwiftUIStruct())

https://developer.apple.com/documentation/swiftui/uihostingcontroller

It allows you to place SwiftUI content in a UIKit application as you would place a UIView or UIViewController in it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.