Using UIKit in SwiftUI
2 min readJan 8, 2024
To use UIKit views in SwiftUI, you need to adopt the SwiftUI protocol UIViewRepresentable
.
Conforming to the UIViewRepresentable Protocol
First, create a structure that implements the two required methods:
makeUIView
: Create an instance of the UIKit view you want to use and return it.updateUIView
: Update the state of the UIKit view based on changes in the SwiftUI view.
Here’s an example of how to use the UIViewRepresentable
protocol to integrate a UILabel
in SwiftUI:
struct LabelView: UIViewRepresentable {
let text: String
func makeUIView(context: Context) -> UILabel {
let label = UILabel()
label.text = text
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
Now you can use this structure in a SwiftUI view just like any other view:
struct ContentView: View {
var body: some View {
LabelView(text: "Hello, World!")
}
}
What’s Next?
You can learn how to use the Coordinator to implement delegates for a UIKit view.
If you want to read the Spanish version of this article, you can find it here: https://asynclearn.com/blog/usando-uikit-en-swiftui/