I created SimpleForm as an easy way to build simple forms in SwiftUI with the ability to validate and return data.
Coming from a web background I'm very used to how forms recognize the fields within them to send data. At the core you don't need to write extra code to submit form data unless we're talking AJAX. With HTML5 we also have built in validation options which make web forms more convenient.
The same functionality is not built into the Form view element in SwiftUI. It does recognize a TextField or a Picker, but does not automatically track the values and can not return you data.
In the full example below it shows you how to add sections, add fields to section with a label, name(just like web for data output), default value, validation, etc. Then with the submit button we can validate the form and return the data.
import SwiftUI
import SimpleForm
struct ContentView: View {
var jamForm = SF()
var body: some View {
// Section One
let sectionOne = SimpleFormSection()
sectionOne.model.fields.append(SimpleFormField(textField: "First Name", labelPosition: .above, name: "first_name", value: "", validation: [.required]))
sectionOne.model.fields.append(SimpleFormField(textField: "Last Name", name: "last_name", value: "", validation:[.required, .regex(#"^\d*$"#, "Please enter numbers only.")]))
sectionOne.model.fields.append(SimpleFormField(textField: "Email", labelPosition: .above, name: "email", value: "", validation: [.required, .email], keyboardType: .emailAddress))
self.jamForm.model.sections.append(sectionOne)
// Section Two
let sectionTwo = SimpleFormSection()
sectionTwo.model.fields.append(SimpleFormField(pickerField: "Greetings", name: "greeting", selection: 2, options: [1,13,24], display: { options in
return AnyView(
List(0 ..< options.count) { row in
HStack {
Rectangle().fill(Color.black).frame(width: 100, height: 100)
Text("\(options[row] as! Int)").frame(minWidth:100)
}
}
)
}))
self.jamForm.model.sections.append(sectionTwo)
return NavigationView {
jamForm
.navigationBarTitle("Simple Form", displayMode: .inline).navigationBarItems(trailing: Button(action: {
let formValues = self.jamForm.getValues()
print(formValues)
let formValid = self.jamForm.isValid()
print("Form Valid: ", formValid)
}){
Text("Submit")
})
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Top comments (1)
Thanks for sharing Super Cool of you