Post

Replies

Boosts

Views

Created

Text insertion in UIViewRepresentable-wrapped UITextField goes haywire after inserting emoji
Folks, I'm trying to understand what I'm missing here. In a SwiftUI project, I've wrapped a UITextView in UIViewRepresentable as a replacement for SwiftUI's TextEditor control, largely so that I can get it to become/resign first responder status. This minimally-viable example works fine, except for one bug that I can't seem to resolve: if I add an emoji anywhere in that text view, then text insertion goes haywire — wherever I have the cursor, the character typed will be inserted, but then the cursor immediately jumps to the end of the text in the field. import SwiftUI struct WrappedTextView: UIViewRepresentable { &#9;&#9;class Coordinator: NSObject, UITextViewDelegate { &#9;&#9;&#9;&#9;@Binding var text: String &#9;&#9;&#9;&#9;var didBecomeFirstResponder: Bool = false &#9;&#9;&#9;&#9;init(text: Binding<String>) { &#9;&#9;&#9;&#9;&#9;&#9;_text = text &#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;func textViewDidChangeSelection(_ textView: UITextView) { &#9;&#9;&#9;&#9;&#9;&#9;DispatchQueue.main.async { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.text = textView.text ?? "" &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} &#9;&#9;} &#9;&#9;@Binding var text: String &#9;&#9;var isFirstResponder: Bool = false &#9;&#9;func makeUIView(context: UIViewRepresentableContext<WrappedTextView>) -> UITextView { &#9;&#9;&#9;&#9;let textView = UITextView() &#9;&#9;&#9;&#9;textView.delegate = context.coordinator &#9;&#9;&#9;&#9;return textView &#9;&#9;} &#9;&#9;func makeCoordinator() -> WrappedTextView.Coordinator { &#9;&#9;&#9;&#9;return Coordinator(text: $text) &#9;&#9;} &#9;&#9;func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<WrappedTextView>) { &#9;&#9;&#9;&#9;uiView.text = text &#9;&#9;&#9;&#9;if isFirstResponder && !context.coordinator.didBecomeFirstResponder { &#9;&#9;&#9;&#9;&#9;&#9;uiView.becomeFirstResponder() &#9;&#9;&#9;&#9;&#9;&#9;context.coordinator.didBecomeFirstResponder = true &#9;&#9;&#9;&#9;} &#9;&#9;} } Credit to this Stack Overflow answer for the above code: https://stackoverflow.com/a/56508132 Can someone help me understand what I'm doing wrong? There's an example project available here, wrapping both UITextField and UITextView in UIViewRepresentable: https://github.com/AngeloStavrow/WrappedTextInputExample
1
0
2.4k
Nov ’20