I am trying to make my SwiftUI Textfield input ignore spaces every time the spacebar button is pressed so that account input data does not contain any spaces.
I saw the code below for achieving this with "proxy binding" but the answer is so concise for me and I am new to { get set }.
Ignore left whitespaces on imput in TextField SwiftUI Combine
I want the code in AccountInput to return if the new input is a space so that it does not go into the textfield & loginViewModel.input.
How can I make this code work?
MAIN VIEW
struct LoginView: View {
@StateObject var loginViewModel = LoginViewModel()
var body: some View {
VStack {
AccountInput(placeholder: "", input: $loginViewModel.input)
}
}
}
ACCOUNT INPUT
struct AccountInput: View {
var placeholder: String
@Binding var input: String
var body: some View {
HStack {
TextField(placeholder, text: Binding(
get: { self.input },
set: {
var newValue = $0
if newValue == " " { // How can I make new values return if a space?
return
}
self.input = newValue
}))
}
}
}
CodePudding user response:
No, we should not return, there should be assignment, because it generates feedback.
It can be like
TextField(placeholder, text: Binding(
get: { self.input },
set: {
var newValue = $0
newValue.removeAll { $0 == " " } // << here !!
self.input = newValue
}))