Serge Vu
Serge Vu

Reputation: 551

How can I programmatically edit TextField's border color in SwiftUI?

Here's the code snippet:

TextField("Email", text: self.$email)
    .padding()
    .overlay(RoundedRectangle(cornerRadius: 1)
                .stroke(Color.black, lineWidth: 1))
SecureField("Password", text: self.$password)
    .padding()
    .overlay(RoundedRectangle(cornerRadius: 1)
                .stroke(Color.black, lineWidth: 1))

Button(action: {
    print("The button was clicked!")
    if loginAndPasswordAreOK() {
        print("Login & Password are OK!")
    } else {
        self.email = ""
        self.password = ""
    }
}, label: {
Text("Log In")
    .fontWeight(.bold)
    .padding()

How can I change email's textfield's border color to red if the login & password were entered incorrectly?

Upvotes: 5

Views: 2937

Answers (1)

Asperi
Asperi

Reputation: 257779

You can use explicit state variable for that, like

@State private var isValid = true

...

TextField("Email", text: self.$email)
    .padding()
    .overlay(RoundedRectangle(cornerRadius: 1)
                .stroke(isValid ? Color.black : Color.red, lineWidth: 1))

...
Button(action: {
    print("The button was clicked!")
    isValid = loginAndPasswordAreOK() 
    if isValid {
     ...

Upvotes: 4

Related Questions