I'm implementing a custom text editor in SwiftUI using a UITextView wrapped in a UIViewRepresentable. The text editor works for basic text entry, but I'm encountering an issue with scrolling behavior. When the UITextView becomes the first responder (when tapped), the parent ScrollView doesn't automatically scroll to make the text view visible. Instead, the scroll position jumps to the last known position (scrolls to a different text view that was previously focused).
Here's my implementation reduced to the minimum:
struct SpacedTextEditor: View { @Binding var text: String var body: some View { MinimalEditor(text: $text) } } private struct MinimalEditor: UIViewRepresentable { @Binding var text: String func makeUIView(context: Context) -> UITextView { let textView = UITextView() textView.backgroundColor = .clear textView.delegate = context.coordinator textView.isScrollEnabled = false textView.text = text return textView } func updateUIView(_ textView: UITextView, context _: Context) { if textView.text != text { textView.text = text } } func makeCoordinator() -> Coordinator { Coordinator(text: $text) } class Coordinator: NSObject, UITextViewDelegate { var text: Binding<String> init(text: Binding<String>) { self.text = text } func textViewDidChange(_ textView: UITextView) { text.wrappedValue = textView.text } } }
The text editor is placed inside a ScrollView in my parent view. How can I ensure that when a user taps on the text editor, the ScrollView properly scrolls to make it fully visible or at least it doesn't jump to where the textfield is not even visible?
I need to use a custom textfield because I need to be able to modify the space between lines, and I didn't find a way to do this using the swiftUI component.