How to Use UIHostingConfiguration to Integrate SwiftUI Views into UIKit Apps
UIHostingController is no longer the only choice.
--
This article is originally published at swiftsenpai.com
Since the release of SwiftUI in 2019, Apple has been striving to enhance the interoperability between SwiftUI and UIKit. In iOS 16, Apple introduced UIHostingConfiguration
, which is a powerful feature that enables developers to use SwiftUI views as UITableView
or UICollectionView
cells.
Recently, I came across an article that showed me another use case for UIHostingConfiguration
that I was not aware of. It turns out that UIHostingConfiguration
allows us to create a SwiftUI view that can be used in UIKit apps. I am extremely excited about this discovery and would like to share the details with you in this article.
How Does It Work
The concept behind is actually pretty straightforward. All we need to do is convert the SwiftUI view into a UIView
. Let me show you how:
let config = UIHostingConfiguration {
Text("This is a SwiftUI view!")
}
let subview = config.makeContentView()
view.addSubview(subview)
If you take a look at the code above, you’ll notice that the makeContentView()
method is where the magic happens. This method takes the SwiftUI view and converts it into a UIView
. This means that we can now use the converted view just like any other UIView
.
What’s great about this approach is that it removes the need to use UIHostingController
for simple UIs, while allowing us to easily access all the cool SwiftUI features that are not available in UIKit.
The Use Case Example
Let’s put what we just learned into practice by creating the following effect in a UIKit app.
Notice that the checkbox is created using a UIButton
, while the agreement string is a SwiftUI view. The reason why I am doing this is to demonstrate how a UIKit component can interact with a SwiftUI view. In most cases, it is always better to include the checkbox as part of the SwiftUI view.
Firstly, let’s create the SwiftUI view and name it AgreementView
.