1

How to show the placeholder if the value of the TextField is equal to "0" in SwiftUI ?

3 Answers 3

1

Here is a right way of doing this, with custom Binding:

struct ContentView: View {
    
    @State private var stringOfTextField: String = String()
    
    var body: some View {
        
        VStack(spacing: 20.0) {
            
            TextField("Input your value Here!", text: Binding.init(get: { () -> String in
                                                                    if (stringOfTextField != "0") { return stringOfTextField }
                                                                    else { return "" } },
                                                                   set: { (newValue) in stringOfTextField = newValue }))
                .textFieldStyle(RoundedBorderTextFieldStyle())
            
            HStack {
                
                Button("set value to 1000") { stringOfTextField = "1000" }
                
                Spacer()
                
                Button("set value to 0") { stringOfTextField = "0" }
                
            }
            
        }
        .padding()
  
    }
    
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. It's actually worked very well!
1

You can use ZStack with TextField + Text and apply opacity depending on current text:

@State
var text = ""

var body: some View {
    let isZero = text == "0"
    ZStack(alignment: .leading) {
        TextField("", text: $text)
            .opacity(isZero ? 0 : 1)
        Text("this is zero")
            .opacity(isZero ? 1 : 0)
    }
}

Comments

1

I would do something like this.

Keep in mind this will block the user from entering "0" as the first character.

struct ContentView: View {

    @State var text = ""
    
    var body: some View {
        TextField("Placeholder", text: $text)
            .onChange(of: text, perform: { value in
                if value == "0" {
                    text = ""
                }
            })
    }
}

If your var is @Binding then use this:

struct ContentView: View {
    
    @Binding var text: String
    
    var body: some View {
        TextField("Placeholder", text: $text)
            .onChange(of: $text.wrappedValue, perform: { value in
                if value == "0" {
                    text = ""
                }
            })
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.