WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to wrap a custom UIView for SwiftUI

Paul Hudson    @twostraws   

Updated for Xcode 14.2

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 as the basis of a rich text editor. 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: NSMutableAttributedString

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

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.attributedText = 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 = NSMutableAttributedString(string: "")

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

Because that uses attributed text, you could add some buttons to enable formatting such as bold, italics, and more.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS 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: 3.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.