SALE: Save 50% on all my books and bundles >>

Basic form design

Paul Hudson    @twostraws   

Fully updated for Xcode 11.4

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 private var enableLogging = false

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

    var body: some View {
        NavigationView {
            Form {
                Picker(selection: $selectedColor, label: Text("Select a color")) {
                    ForEach(0 ..< colors.count) {
                        Text(self.colors[$0]).tag($0)
                    }
                }.pickerStyle(SegmentedPickerStyle())

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

                Button(action: {
                // activate theme!
                }) {
                    Text("Save changes")
                }
            }.navigationBarTitle("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 more than 10.

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred by integrating Instabug's SDK in one minute. You will automatically receive device data, network logs, and reproduction steps with every bug and crash report.

Learn more and get started for free

Sponsor Hacking with Swift and reach the world's largest Swift community!

Snapthread is a casual video editor and slideshow maker that makes discovering, compiling and sharing your favorite memories effortless.

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5