I have custom text field, and when I typing text I want to clear text inside of the text field by clear button, I did not find any solution, I am try to solve by similar question, but still same problem, any idea?
view:
struct TextView : View {
@State var text = ""
var body: some View{
VStack {
CustomTxt(txt: self.$txt)
Button(action: {
txt = ""
}, label: {
Image("clear text field")
})
}
}
textfield:
struct CustomTxt : UIViewRepresentable {
@Binding var txt : String
func makeCoordinator() -> Coordinator {
return ResizableTextField.Coordinator(parent1: self)
}
func makeUIView(context: Context) -> UITextView {
let view = UITextView()
view.delegate = context.coordinator
return view
}
func updateUIView(_ uiView: UITextView, context: Context) {
DispatchQueue.main.async {
self.height = uiView.contentSize.height
}
}
class Coordinator : NSObject, UITextViewDelegate {
var parent : CustomTxt
init(parent1 : CustomTxt) {
parent = parent1
}
func textViewDidBeginEditing(_ textView: UITextView) {
if self.parent.txt == "" {
textView.text = ""
}
}
func textViewDidChange(_ textView: UITextView) {
DispatchQueue.main.async {
self.parent.height = textView.contentSize.height
self.parent.txt = textView.text
}
}
}
}
CodePudding user response:
When binding is changed the UIViewRepresentable.updateUIView
is called, so you have to updated wrapped UIKit view there.
In your case it is
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = txt // << here !!
DispatchQueue.main.async {
self.height = uiView.contentSize.height
}
}
thus tap button result in update wrapped UITextView with empty string.