SwiftUI style update onEditChanged does not pop up keyboard

Viewed 49

I am trying to update the style of the HStack containing my text box when the Textbox is selected. In the example below, I want the text box to have a red border when selected, otherwise the border should be gray.

My issue is that the textbox seems to go through an intermediate transition that I don't want, which is the border is updated to red, but the keyboard doesn't pop up until I select the textbox again (The textbox moves up a bit and then goes back down). It seems that there is some issue with the ordering of how the view refresh happens.

@State private var text: String
@State private var textFieldSelected: Bool = false
        
var body: some View {
        let stack = HStack {
            TextField("Enter name", text: $text, onEditingChanged: {
                (changed) in
                    textFieldSelected = changed
            })
        }
        
        if (textFieldSelected) {
            stack
                .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.red, lineWidth: 1))
        } else {
            stack
                .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color.gray, lineWidth: 1))
        }
    }

Here's a video example of the existing behavior:

Video Example

1 Answers

Make it even simpler by using ternary condition for the border and the issue won't appear

struct ContentView : View {
    @State private var text: String = ""
    @State private var textFieldSelected: Bool = false
            
    var body: some View {
        HStack {
            TextField("Enter name", text: $text, onEditingChanged: {
                (changed) in
                    textFieldSelected = changed
            })
        }
        .overlay(RoundedRectangle(cornerRadius: 10).stroke(textFieldSelected ? Color.red : Color.gray, lineWidth: 1))
    }
}
    

Tested on iPhone 8 Plus iOS 14

Related