如何在 SwiftUI 中以编程方式编辑 TextField 的边框颜色?

Ser*_* Vu 5 ios swift swiftui

这是代码片段:

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()
Run Code Online (Sandbox Code Playgroud)

如果登录名和密码输入不正确,如何将电子邮件文本字段的边框颜色更改为红色?

Asp*_*eri 4

您可以为此使用显式状态变量,例如

@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 {
     ...

Run Code Online (Sandbox Code Playgroud)