Updated for Xcode 13.3
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 Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.