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

4
这是代码片段:
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()

如果用户输入了错误的登录名或密码,如何将电子邮件文本框的边框颜色更改为红色?

1个回答

3
您可以使用显式状态变量来实现,例如:
@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 {
     ...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接