如果 SwiftUI 中的值等于“0”,则显示占位符

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

在 SwiftUI 中,如果 TextField 的值等于“0”,如何显示占位符?

您可以将 ZStackTextField + Text 结合使用,并根据当前文本应用 opacity

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

这是使用自定义绑定的正确方法:

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

我会做这样的事情。

请记住,这将阻止用户输入“0”作为第一个字符。

struct ContentView: View {

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

如果你的 var@Binding 那么使用这个:

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