Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use UIViewController and UIView in SwiftUI?

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?

like image 582
Viktor Maric Avatar asked Jun 18 '19 17:06

Viktor Maric


People also ask

Does SwiftUI use UIView?

SwiftUI calls the makeUIView method once to let you instantiate the UIKit view. For any redraw, SwiftUI will call into the updateUIView method to let you update the underlying UIKit view.

Can you combine SwiftUI and UIKit together?

SwiftUI works seamlessly with the existing UI frameworks on all Apple platforms. For example, you can place UIKit views and view controllers inside SwiftUI views, and vice versa.

How do I present a UIView in Swift?

present the gray UIView like you would usually present a ViewController (appearing bottom up and user can slide down to dismiss). The bottomBar is a ContainerView and should not change by switching between the VC's, only the gray UIView which you can see in the 2nd picture.


1 Answers

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.

like image 103
ntrupin Avatar answered Sep 30 '22 00:09

ntrupin