Skip to main content

How to wrap a custom UIView for SwiftUI

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to wrap a custom UIView for SwiftUI 관련

SwiftUI by Example

Back to Home

How to wrap a custom UIView for SwiftUI | SwiftUI by Example

How to wrap a custom UIView for SwiftUI

Updated for Xcode 15

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.

Similar solutions…
Answering the big question: should you learn SwiftUI, UIKit, or both? | SwiftUI by Example

Answering the big question: should you learn SwiftUI, UIKit, or both?
Frequently asked questions about SwiftUI | SwiftUI by Example

Frequently asked questions about SwiftUI
Wrap up: our SwiftUI project is complete | SwiftUI by Example

Wrap up: our SwiftUI project is complete
How to draw a custom path | SwiftUI by Example

How to draw a custom path
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks

이찬희 (MarkiiimarK)
Never Stop Learning.