The following would work except that I'm required to use Binding.
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: "Amazon River Branch", text: $tenantID)
HStack {
Text("Shop ID: ")
TextField("Amazon River Branch", text: $tenantID)
.onChange(of: tenantID) { newValue in
tenantID = textFilter(value: newValue)
}
}
}.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: { text.wrappedValue = textFilter(value: $0) }
)
Text(label)
TextField(placeHolder, text: newText)
}
}
func textFilter(value: String) -> String {
let pattern = "[^A-Za-z0-9]+"
return value.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: