I need to disable space inputs in my username text fields on Swift UI, how would I go about that?
Current code:
@State private var username = ""
CustomInputField(imageName: "at.circle.fill", placeholderText: "Username", text: $username)
Support is greatly appreciated! :)
CodePudding user response:
What you need is to create an observable object and filter the spaces every time the string changes. It should be pretty straightforward:
import SwiftUI
struct ContentView: View {
@ObservedObject private var usernameManager = UsernameManager()
var body: some View {
VStack(alignment: .trailing, spacing: 0) {
Text("Username:")
TextField(
usernameManager.string,
text: $usernameManager.string
)
.keyboardType(.asciiCapable)
.multilineTextAlignment(.trailing)
.onChange(
of: usernameManager.string,
perform: usernameManager.editingChanged
)
}.padding(.trailing, 25)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
class UsernameManager: ObservableObject {
@Published var string: String = ""
func editingChanged(_ string: String) {
self.string = string.filter(\.isWhitespace.negated)
}
}
extension Bool {
var negated: Bool { !self }
}