NEW: Learn SwiftUI with my free YouTube video series! >>

< Basic form design   Pickers in forms >

Breaking forms into sections

SwiftUI’s forms often work best when broken into sections, just like regular lists of content. How you break them up is down to you, but usually it works best when you group things according to their purpose – if it were an order page you might put items in one group, customization in another, and delivery in a third.

Helpfully, form sections are identical to list sections, which means you can re-use the same code in both places. So, you can add a header and/or footer to your sections, or use neither and just get some on-screen spacing between your sections.

As an example, this creates a form with two sections – the first with a segmented control and toggle, and the second with a save button:

struct ContentView : View {
    @State var enableLogging = false

    @State var selectedColor = 0
    @State var colors = ["Red", "Green", "Blue"]

    var body: some View {
        NavigationView {
            Form {
                Section(footer: Text("Note: Enabling logging may slow down the app")) {
                    SegmentedControl(selection: $selectedColor) {
                        ForEach(0 ..< colors.count) {
                            Text(self.colors[$0]).tag($0)
                        }
                    }

                    Toggle(isOn: $enableLogging) {
                        Text("Enable Logging")
                    }
                }

                Section {
                    Button(action: {
                    // activate theme!
                    }) {
                        Text("Save changes")
                    }
                }
            }.navigationBarTitle(Text("Settings"))
        }
    }
}

LEARN SWIFTUI FOR FREE I wrote a massive, free SwiftUI tutorial collection, and also have a growing list of free SwiftUI tutorials on YouTube – get started today!

< Basic form design   Pickers in forms >
MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 4.5/5

Click here to visit the Hacking with Swift store >>