是否可以使SwiftUI Textfield简单地忽略空格键?
我想这样做,当用户输入他们的注册/登录详细信息时,空格键被忽略,因为该数据不需要空格。
我找到的其他解决方案仍然允许用户在文本字段中输入空格,但然后在下一个字符输入时擦除它们,这是不理想的,例如这篇文章:忽略TextField输入中的左侧空白
我需要Textfield完全忽略空格。
struct IgnoreSpacesTextfield: View {
@State private var email: String = ""
var body: some view {
TextField("e-mail", text: $email)
// ^ needs to ignore space-bar entry
}
}
试试这个自定义TextField:
import SwiftUI
struct ContentView: View {
@State private var test = ""
var body: some View {
//completely ignore space
CustomTextField("enter", text: $test)
}
}
//custom textfield
struct CustomTextField: View {
let label: LocalizedStringKey
@Binding var text: String
init(_ label: LocalizedStringKey, text: Binding<String>) {
self.label = label
self._text = Binding(projectedValue: text)
}
var body: some View {
TextField(label, text: $text)
.onChange(of: text) { _ in
//try one of these
//input = input.replacing(" ", with: "")
//input = input.replacingOccurrences(of: " ", with: "")
//input = input.filter{ s in s != " "}
}
}
}