Using SwiftUI and UIKit together
SwiftUI and UIKit can be used together. SwiftUI can be embedded in a ViewController. Conversely, UIKit Views can also be adapted for use with SwiftUI.
SwiftUI to UIKit
Personally, I think using SwiftUI in UIKit is easier than the opposite. So, let's look at it first.
let vc = UIHostingController(rootView: MyView())
The SwiftUI layer is easy to use in UIKit like this. You can wrap SwiftUI with UIHostingController
and use it.
UIKit to SwiftUI
Using UIKit components in Swift is a little bit harder than the opposite. However, it is important that it is possible.
Let's look at the example of UIView of UIKit. UIView is available in SwiftUI like this. If you create a wrapper that conforms to UIViewRepresentable, it will work just like any other SwiftUI view.
struct MySwiftUIView: UIViewRepresentable {
func makeUIView(context: Context) -> UIViewType {
// Create View
let view = UIView()
return view
}
func updateUIView(_ view: UIViewType, context: Context) {
// Modify View
}
}
You can use it in SwiftUI like this.
struct MyView: View {
var body: some View {
MySwiftUIView()
}
}
Other UIKit components are also available to be used in SwiftUI. However, it is mostly similar to what we have seen above. So, we will not go through it, but if you want you can refer to Apple's official SwiftUI tutorial called Interfacing with UIKit.