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:
UIViewRepresentable
.makeUIView()
method that will return our text view.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% 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.
Link copied to your pasteboard.