Usefz89
Usefz89

Reputation: 73

Show Placeholder if the value equal to "0" in SwiftUI

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

Upvotes: 1

Views: 629

Answers (3)

Alhomaidhi
Alhomaidhi

Reputation: 666

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 = ""
                }
            })
    }
}

Upvotes: 1

Phil Dukhov
Phil Dukhov

Reputation: 87605

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)
    }
}

Upvotes: 1

swiftPunk
swiftPunk

Reputation: 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()
  
    }
    
}

Upvotes: 1

Related Questions