How to take advantage of SwiftUI inside UIKit?

Brahim Siempay
iOS Senior Tips

--

Photo by charlesdeluvio on Unsplash

It is possible to use SwiftUI views and controls within a UIKit app, and vice versa. Here is an example of how you can use a SwiftUI view within a UIKit app:

First, create a SwiftUI view that you want to use in your UIKit app. For example:

import SwiftUI

struct MySwiftUIView: View {
var body: some View {
Text("Hello, World!")
}
}

In your UIKit app, create a UIHostingController object and pass it the SwiftUI view as an argument. For example:

import UIKit

class MyViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let hostingController = UIHostingController(rootView: MySwiftUIView())
self.addChild(hostingController)
self.view.addSubview(hostingController.view)
hostingController.didMove(toParent: self)
}
}

You can then use the UIHostingController object’s view property to add the SwiftUI view to your UIKit app’s view hierarchy, like you would with any other UIView. For example:

let hostingController = UIHostingController(rootView: MySwiftUIView())
self.view.addSubview(hostingController.view)

Keep in mind that UIKit and SwiftUI use different approaches to layout and design, so you may need to make some adjustments to ensure that your SwiftUI views look and behave as expected when used within a UIKit app.

Learn more at HowtoInSwift:

--

--