I have three sets of Text and TextField. And I need to filter each TextField entry. I have gotten a function to filter the TextField entry from this website (https://zenn.dev/yorifuji/articles/swiftui-textfield-filter). Finally, I have the following lines of code.
import SwiftUI
struct ContentView: View {
@State var username = ""
@State var password = ""
@State var tenantID = ""
var body: some View {
VStack {
makeForm(label: "Username: ", placeHolder: "123456", text: $username)
makeForm(label: "Password: ", placeHolder: "abcdefg", text: $password)
makeForm(label: "Shop ID: ", placeHolder: "123456", text: $tenantID)
}.padding(.horizontal, 40.0)
}
@ViewBuilder
private func makeForm(label: String, placeHolder: String, text: Binding<String>) -> some View {
HStack {
let newText = Binding<String>(
get: { text.wrappedValue },
set: { filter(value: $0) }
)
Text(label)
TextField(placeHolder, text: newText)
}
}
func filter(value: String) -> String {
let validCodes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
let sets = CharacterSet(charactersIn: validCodes)
return String(value.unicodeScalars.filter(sets.contains).map(Character.init))
}
}
Well, I don't know how to use the Binding with get and set, which I believe is what I need. Yet, I get a warning at the following line.
set: { filter(value: $0) }
What I need to do is set the filtered value to each TextField. What am I doing wrong? Thanks.