1

I've got a SwiftUI TextEditor that appears once a button is pressed. What I can't figure out is, how to make the TextEditor the first responder when it appears.

What I've tried is adding a .focused modifier to the TextEditor and then setting the focused Bool value to true inside .onAppear. But still the keyboard only shows up when its pressed.


import SwiftUI

struct ContentView: View {
    
    @State var showTextField : Bool = false
    @State private var currentEditText : String = "Some text"
    @FocusState private var editTextFieldFocus: Bool
    
    
    var body: some View {
        VStack {
            Button {
                showTextField.toggle()
            } label: {
                Text("Show Text Field")
            }

            Text("Hello, world!")
                .padding()
            if showTextField{
                TextEditor(text: $currentEditText)
                    .focused($editTextFieldFocus)
                    .onAppear {
                        editTextFieldFocus = true
                    }
            }
            
        }
    }
}
unknown
  • 788
  • 9
  • 24
  • Does this answer your question? [SwiftUI: How to make TextField become first responder?](https://stackoverflow.com/questions/56507839/swiftui-how-to-make-textfield-become-first-responder) – Magnas Nov 22 '21 at 08:26
  • My question is slightly different as the text field is hidden initially. I have already tried what is suggested in that question and it doesn't work in this situation. – unknown Nov 22 '21 at 09:11
  • 1
    The problem was that the `editTextFieldFocus` is toggled before the `TextField` shows up. I just set `editTextFieldFocus ` to true inside `async` and it works as expected. – unknown Nov 22 '21 at 14:05

0 Answers0