如何在 SwiftUI 中以编程方式编辑 TextField 的边框颜色? [英] How can I programmatically edit TextField's border color in SwiftUI?

查看:32
本文介绍了如何在 SwiftUI 中以编程方式编辑 TextField 的边框颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码片段:

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?

推荐答案

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

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

这篇关于如何在 SwiftUI 中以编程方式编辑 TextField 的边框颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆