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

安稳与你 提交于 2020-12-11 00:47:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/64683613/how-can-i-programmatically-edit-textfields-border-color-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!