ArielSD
ArielSD

Reputation: 909

How can you change TextField state based on input in SwiftUI?

I'm pretty new to SwiftUI, so I'd love any help!

I'm looking to build a TextField that shows an error state based on the validation of the text.

For example, if the TextField is meant to collect an email, show an error if the text doesn't contain @. Let's say the error state would change the border color of the TextField to Color.green.

I was thinking of approaching this with a validating closure, but I'm still unsure of how to change the actual visual state of the TextField.

I see that we can can change border color based on editing state - should I just declare something like a @State var isError?

I've also tried holding TextFieldStyle as a @State, but that seems to be a protocol with an associated type, which I haven't been able to get around:

Something like:

TextField("",
              text: $text,
              onEditingChanged: { _ in
                self.style = CustomErrorStyle()

Please let me know if I can clarify at all, thanks!

Upvotes: 1

Views: 1899

Answers (1)

nicksarno
nicksarno

Reputation: 4235

The $text value will be constantly updated, so you can just update the TextField formatting based on the current value of text. Here is a sample:

struct TextFieldTest: View {
    
    @State var text: String = ""
    
    var body: some View {
        TextField("Placeholder", text: $text)
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 25.0)
                    .stroke(
                        text == "" ?
                        Color.gray :
                        textIsAppropriate() ?
                        Color.green :
                        Color.red
                        , lineWidth: 2.0)
            )
    }
    
    func textIsAppropriate() -> Bool {
        if text.contains("@") {
            return true
        }
        return false
    }
}

Of course, the solution in @Asperi's comment above also works if you prefer to only change the formatting when a user taps a button!

Upvotes: 4

Related Questions