DEV Community

JoeShon Monroe
JoeShon Monroe

Posted on

SimpleForm for SwiftUI

I created SimpleForm as an easy way to build simple forms in SwiftUI with the ability to validate and return data.

Try It Here 🙂

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))


        // 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( 100, height: 100)
                        Text("\(options[row] as! Int)").frame(minWidth:100)





        return NavigationView {
                .navigationBarTitle("Simple Form", displayMode: .inline).navigationBarItems(trailing: Button(action: {
                    let formValues = self.jamForm.getValues()
                    let formValid = self.jamForm.isValid()
                    print("Form Valid: ", formValid)

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {

Top comments (1)

yourdevguy profile image
Mike Haslam

Thanks for sharing Super Cool of you