Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextField foreground color issue

Tags:

swiftui

I'm trying to make real time email validation, but the simulator has strange behaviour. When the email IS NOT valid, it should be red, when it IS valid, the color of the text should be black, but some characters stay red.

struct EmailText: View {
    @State var textFieldValue: String = ""
    
    private func isValid(_ s: String) -> Bool {
        // not real validation function, just for simplicity
        return Int.random(in: 0 ... 1) == 1
    }
    
    var body: some View {
        TextField("", text: $textFieldValue)
            .foregroundColor(isValid(textFieldValue) ? .black : .red)
            .padding()
    }
}

demo

I have updated the validation function from regex to simple condition, to exclude regex as a possible issue.

like image 458
filip.karas Avatar asked Oct 21 '25 06:10

filip.karas


1 Answers

Solution: disable autocorrection.

TextField("", text: $textFieldValue)
            .foregroundColor(isValid(textFieldValue) ? .black : .red)
            .padding()
            .autocorrectionDisabled() // <----

Most certainly a SwiftUI bug that causes interference between the text highlighting of spell check warnings and the foreground color.

like image 142
JanBrinker Avatar answered Oct 24 '25 09:10

JanBrinker



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!