Is it possible to make a SwiftUI Textfield simply ignore space-bar key-strokes?
I want to make it so that when a user enters their sign-up / login details that the space bar is ignored since that data does not need spaces.
Other solutions I found for this still allow the user to enter spaces in the textfield but then erase them on the next character entered, which is not ideal, such as this SO article:
Ignore left whitespaces on imput in TextField SwiftUI Combine
I need the Textfield to completely ignore the space-bar.
struct IgnoreSpacesTextfield: View {
@State private var email: String = ""
var body: some view {
TextField("e-mail", text: $email)
// ^ needs to ignore space-bar entry
}
}
CodePudding user response:
Try this custom 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 != " "}
}
}
}