NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to wrap a custom UIView for SwiftUI

Paul Hudson    @twostraws   

Fully updated for Xcode 11.1

Although SwiftUI does a good job of providing many of UIKit’s UIView subclasses, it doesn’t have them all yet at this time. Fortunately, it’s not hard to create custom wrappers for a UIView that you want.

As an example, let’s create a simple SwiftUI wrapper for UITextView. This takes four steps:

  1. Creating a struct that conforms to UIViewRepresentable.
  2. Defining one property that stores the text string we are working with.
  3. Giving it a makeUIView() method that will return our text view.
  4. Adding a updateUIView() method that will be called whenever the data for the text view has changed.

In code we end up with this:

struct TextView: UIViewRepresentable {
    @Binding var text: String

    func makeUIView(context: Context) -> UITextView {
        return UITextView()
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
    }
}

And that’s it! You can now immediately use the TextView component in SwiftUI views, such as this one:

struct ContentView : View {
    @State var text = ""

    var body: some View {
        TextView(text: $text)
            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
    }
}

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 2.0/5