使iOS SwiftUI TextField拒绝错误的数字输入



My iOS SwiftUI TextField允许用户输入Int。如果用户键入错误的输入字符,如"abc";而不是";123〃;,我想在我的Text(我写textField.Text的地方(中的错误消息中显示坏字符,并且我想让textField的键盘一直在屏幕上,直到用户提供正确的输入。如何实现这一点?提前谢谢。macOS Catalina 10.15.6上的Xcode 11.6。

struct ContentView: View {
@State private var value: Int? = nil;
@State private var text: String = "";
var body: some View {
VStack {
TextField(
"Enter an integer:",
value: $value,
formatter: NumberFormatter(),
onCommit: {
guard let value: Int = self.value else {
self.text = "Bad input "(textField.text)".";
//Do not dismiss the TextField's keyboard.
return;
}
//Dismiss the TextField's keyboard.
self.text = "The product is (2 * value).";
}
)
.keyboardType(.numbersAndPunctuation)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text(text)
}
.padding([.leading, .trailing], 16)
}
}

下面的代码为您提供了一个在用户输入时验证文本字段中的文本的想法。

struct ContentView: View {
@State private var textNumber    : String = ""
@State private var isNumberValid : Bool   = true
var body: some View {
VStack {

TextField("Enter an integer:", text: numberValidator())
.keyboardType(.numbersAndPunctuation)
.textFieldStyle(RoundedBorderTextFieldStyle())

if !self.isNumberValid {
Text("Bad input "(textNumber)".")
.font(.callout)
.foregroundColor(Color.red)
}
}
.padding([.leading, .trailing], 16)
}
private func numberValidator() -> Binding<String> {
return Binding<String>(
get: {
return self.textNumber
}) {
if CharacterSet(charactersIn: "1234567890").isSuperset(of: CharacterSet(charactersIn: $0)) {
self.textNumber = $0
self.isNumberValid = true
} else {
self.textNumber = $0
//self.textNumber = ""
self.isNumberValid = false
}
}
}
}

下面的代码片段为您提供了一个在用户使用Get,Set值输入时验证文本字段内文本的想法

let checkValue = Binding<String>(
get: {
self.value
},
set: {
self.value = $0
}
)

我希望它能对你有所帮助

struct ContentView: View {
@State private var value: String = ""
@State private var text: String = ""
var body: some View {
let checkValue = Binding<String>(
get: {
self.value
},
set: {
self.value = $0
}
)
return VStack {
TextField("Enter an integer:",text: checkValue)
.keyboardType(.numbersAndPunctuation)
.textFieldStyle(RoundedBorderTextFieldStyle())
Text("Bad interger: (Int(self.value) != nil ? "" : self.value)").foregroundColor(Color.red)

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

相关内容

  • 没有找到相关文章

最新更新