3

I have this code:

struct MyTestScreen: View {

    @State var text1 = ""
    @State var text2 = ""

    var body: some View {
        VStack {
            TextField("text1", text: self.$text1)
        
            TextField("text2", text: self.$text2)
        }
    }
}

How can I change focus on text2 TextField, when I fill text1 and press "return"?

pawello2222
  • 46,897
  • 22
  • 145
  • 209
alexbayker
  • 882
  • 9
  • 19
  • 1
    This is not currently possible using *pure* SwiftUI. You may take a look at these answers: [Focus on the next TextField/SecureField in SwiftUI](https://stackoverflow.com/questions/58422440/focus-on-the-next-textfield-securefield-in-swiftui) and [How to move to next TextField in SwiftUI?](https://stackoverflow.com/questions/58673159/how-to-move-to-next-textfield-in-swiftui) – pawello2222 Aug 07 '20 at 12:02

1 Answers1

0

this should be possible with the code as below.

@State private var isFirstTextFieldFocused = false
@State private var isSecondTextFieldFocused = false
        
@State private var firstText: String = ""
@State private var secondText: String = ""

 var body: some View {
    VStack {
        TextField("First text field", text: $firstText)
            .padding()
            .border(Color.white, width: isFirstTextFieldFocused ? 2 : 0)
            .scaleEffect(isFirstTextFieldFocused ? 1.1 : 1)
            .focusable(true) { focused in
                isFirstTextFieldFocused = focused
            }
                    
        TextField("Second text field", text: $secondText)
            .padding()
            .border(Color.white, width: isSecondTextFieldFocused ? 2 : 0)
            .scaleEffect(isSecondTextFieldFocused ? 1.1 : 1)
            .focusable(true) { focused in
                isSecondTextFieldFocused = focused
            }
    }
}

Now the textFields should be focusable and you would just need to handle the text input.