Disable return key in swiftui textfield

Viewed 192

I want to enable pressing on the keyboard return key only when a condition occurs.
For example:

SecureField("", text:$password)
    .focused($passwordFocused)
    .onSubmit {
        if password.count >= 8 {
            joinNetwork()
        }
    }
    .submitLabel(.join)

I want to make the return key disabled if the password does not hit the condition. Or at least change the color of the return button to gray.

1 Answers

use .onChange to update state variables as user types. here is a small example that changes the password bullet color from pink to black based on password length. alter this for your purposes

SecureField("", text:$password)
    .onChange(of: password, perform: { _ in
        isPasswordViable = (password.count >= 8)
    })
    .onSubmit {
        guard isPasswordViable else { return }
        print("submitted \(password)")
    }
    .foregroundColor(isPasswordViable ? .black : .pink)
Related