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

< Working with forms   Breaking forms into sections >

Basic form design

SwiftUI’s forms work as containers, just like HStack and VStack, which means you can add other views inside it as needed. However, they automatically adapt the behavior and styling of some controls so they fit better in the form environment.

For example, this creates a form with a toggle, a segmented control, and a button:

struct ContentView : View {
    @State var enableLogging = false

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

    var body: some View {
        NavigationView {
            Form {
                SegmentedControl(selection: $selectedColor) {
                    ForEach(0 ..< colors.count) {
                        Text(self.colors[$0]).tag($0)
                    }
                }

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

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

When that code is run you’ll see two things that are fundamental to the behavior of forms:

  • On iOS the form automatically adopts the style of a grouped list, so users see a scrolling selection of options.
  • The button has adapted itself to look like an actionable list row – it’s left-aligned and in blue.

You can have as many rows in your form as you need, but remember to use groups if you need to past 10.

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!

< Working with forms   Breaking forms into sections >
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!

Click here to visit the Hacking with Swift store >>