NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Basic form design

Paul Hudson    @twostraws   

Updated for Xcode 12.0

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 Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.

Start your free trial!

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

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.3/5

Link copied to your pasteboard.