输入Int的iOS SwiftUI TextField缺少占位符

时间:2020-08-17 08:55:41

标签: ios swiftui textfield placeholder

我希望我的iOS SwiftUI TextField显示占位符“输入整数:”,但是TextField显示0(var值)。当用户删除0时,会出现占位符“输入整数:”。如何在不使用户先删除0的情况下出现占位符“输入整数:”?先感谢您。 macOS Catalina 10.15.6上的Xcode 11.6。

struct ContentView: View {
    @State private var value: Int = 0;
    @State private var text: String = "";
    
    var body: some View {
        VStack {
            TextField(
                "Enter an integer:",
                value: $value,
                formatter: NumberFormatter(),
                onCommit: {self.text = "The product is \(2 * self.value).";}
            )
            .keyboardType(.numbersAndPunctuation)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            
            Text(text)
        }
        .padding([.leading, .trailing], 16)
    }
}

1 个答案:

答案 0 :(得分:0)

要为占位符提供格式为TextField的占位符,我们需要使用可选的值持有者。

这是一个固定的变体

demo

struct ContentView: View {
    @State private var value: Int?
    @State private var text: String = ""

    var body: some View {
        VStack {
            TextField(
                "Enter an integer:",
                value: $value,
                formatter: NumberFormatter(),
                onCommit: {self.text = "The product is \(2 * (self.value ?? 0)).";}
            )
            .keyboardType(.numbersAndPunctuation)
            .textFieldStyle(RoundedBorderTextFieldStyle())

            Text(text)
        }
        .padding([.leading, .trailing], 16)
    }
}