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.
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.