Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus on next TextField in VStack

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"?

like image 760
alexbayker Avatar asked Feb 28 '26 14:02

alexbayker


1 Answers

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.

like image 196
Yoorque Avatar answered Mar 04 '26 11:03

Yoorque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!