SwiftUI and UIKit “talk” by UIViewRepresentable

Goal栈
5 min readJun 5, 2020

OK, as the title side, when you are trying to start embed SwiftUI into your exist project, you may facing to use UIKit in SwiftUI.

In your project, you made a gorgeous customised UIView, and you just want to use it directly in SwiftUI. How?

By UIViewRepresentable .

Background

You have the most beautiful text field like below:


class
CurrencyTextField: UITextField {
xxx
}

You heard of SwiftUI is very cool, you want to use it. Now you are trying how to use TextField in SwiftUI by creating an CurrencyView:

struct CurrencyView: View {    @State var textFieldString = ""    var body: some View {       VStack() {           TextField("Input your currency", text: $textFieldString)           .textFieldStyle(RoundedBorderTextFieldStyle())           Spacer()     }.padding()
}
}struct CurrencyView_Previews: PreviewProvider { static var previews: some View { CurrencyView(dismissAction: nil) }}

The result is:

--

--