// TextView - multiline textarea input
struct TextView: UIViewRepresentable {
@Binding var text: String
@State var textStyle: UIFont.TextStyle = UIFont.TextStyle.body
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.font = UIFont.preferredFont(forTextStyle: textStyle)
textView.autocapitalizationType = .sentences
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.delegate = context.coordinator
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
}
func makeCoordinator() -> Coordinator {
Coordinator($text)
}
class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
init(_ text: Binding<String>) {
self.text = text
}
func textViewDidChange(_ textView: UITextView) {
self.text.wrappedValue = textView.text
}
}
}
// This is a container view showing how to render TextView.
struct TextContainerView: View {
// Define local variable which will be changed from textarea.
@State var description: String = "Hello World"
var body: some View {
VStack(alignment: .leading) {
// Pass description variable as bound variable to update it in parent view from within
// the child textarea view.
TextView(text: $description)
// By default textarea won't have any markings - add padding to it and draw rounded
// rectange as overlay to display textarea as available field in the form.
.padding(5)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color(UIColor.systemGray5), lineWidth: 1)
)
}
}
}
At this moment TextField allows only single-line text input, this component introduces TextView which renders input field that allows user to enter multiple lines of text.