How to use UITextView in SwiftUI

Issue #747

Need to use Coordinator conforming to UITextViewDelegate to apply changes back to Binding

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import SwiftUI
import UIKit

struct MyTextView: UIViewRepresentable {
@Binding
var text: String

final class Coordinator: NSObject, UITextViewDelegate {
let parent: MyTextView

init(parent: MyTextView) {
self.parent = parent
}

func textViewDidChange(_ textView: UITextView) {
if textView.text != parent.text {
parent.text = textView.text
}
}
}

func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}

func makeUIView(context: Context) -> UITextView {
let view = UITextView()
view.isScrollEnabled = true
view.isEditable = true
view.isUserInteractionEnabled = true
view.font = UIFont.preferredFont(forTextStyle: .body)
view.delegate = context.coordinator
return view
}

func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
}

Comments