skip to content

User Input and Controls

Buttons, pickers, forms, text fields with focus, gestures and drag and drop: how SwiftUI takes input. Interviewers ask for a working form and for gesture conflicts resolved cleanly.

on this pageshow

explore

questions

22

In SwiftUI, how do you bind a Toggle and a Picker over an enum to a settings screen's state?

level: juniorimportance: must knowfreq 75%

answer

  1. two-way bindings, not values
  2. Toggle wants a Binding<Bool>
  3. tag type equals selection type
  4. ForEach tags each row with its id

basics

~20 s

Bind a Toggle to a Bool with Toggle("Title", isOn: $flag) and a Picker to an enum with Picker("Title", selection: $choice); give every row a tag of that enum type, which ForEach over an Identifiable enum does for you.

solid answer

~50 s

Both controls take a two-way binding to state the screen owns. `Toggle("Download on Wi-Fi only", isOn: $wifiOnly)` reads and writes a `Bool`. A `Picker` takes `selection:` bound to any `Hashable` value, usually an enum that is `CaseIterable` and `Identifiable` with `var id: Self { self }`. Each row is matched to a selection value through its tag: write `.tag(SkipInterval.fifteen)` by hand, or build the rows with `ForEach(SkipInterval.allCases)`, which tags each row with the element's `id` — so the `id` type must be the selection type. The picker then shows the matching row as selected and writes the tapped row's tag back. How both controls look depends on context: inside a `Form` on iOS a toggle is a switch row and a picker is a row showing its current value, and `toggleStyle(_:)` or `pickerStyle(_:)` override that.

code

swift · 22 lines
swift
import SwiftUI

enum SkipInterval: Int, CaseIterable, Identifiable {
    case ten = 10, fifteen = 15, thirty = 30
    var id: Self { self }
}

struct PlaybackSettings: View {
    @State private var downloadOnWiFiOnly = true
    @State private var skipInterval: SkipInterval = .fifteen

    var body: some View {
        Form {
            Toggle("Download on Wi-Fi only", isOn: $downloadOnWiFiOnly)
            Picker("Skip forward", selection: $skipInterval) {
                ForEach(SkipInterval.allCases) { interval in
                    Text("\(interval.rawValue) seconds")
                }
            }
        }
    }
}

go deeper

for a junior

Recall that Toggle binds to a Bool with isOn and Picker binds to a Hashable selection, and that rows are matched by tag, not by their text.

for a middle

Explain how ForEach supplies tags from each element's id and why the id type must equal the selection type for an enum picker.

for a senior

Show that you model settings as enums with stable cases, keep one source of truth, and know which container changes a control's style.

for a principal

Frame the choice of enum-backed settings as a team convention that keeps persisted values, pickers and the code that reads them consistent.

## What the two controls need A settings screen in SwiftUI is mostly controls bound to state. **`Toggle`** and **`Picker`** are the two you write first, and both follow the same rule: the control does not own the value, it holds a **`Binding`** to a value the screen owns, usually in `@State` or in an observable model. - `Toggle` takes `isOn:` — a `Binding<Bool>`. Pass `$downloadOnWiFiOnly`, the projected value of a `@State var downloadOnWiFiOnly = true`. - `Picker` takes `selection:` — a `Binding<SelectionValue>`, where `SelectionValue` is any `Hashable` type. - Both have a convenience initialiser whose first argument is a title string, which SwiftUI turns into a `Text` label. Passing a plain `Bool` instead of a binding does not compile. Passing `.constant(true)` compiles but the switch can never change, because a constant binding ignores writes. ## How a Picker knows which row is which A `Picker` matches rows to values through **tags**. Each row view carries a tag set with `tag(_:)`, and the picker: 1. reads the current `selection` and shows the row whose tag equals it as selected; 2. when the user picks a row, writes that row's tag into the binding. Apple's documentation states the rule plainly: the type of each tag must match the type of the bound state variable. For an enum that is simple, because each tag is a case: ```swift Picker("Skip forward", selection: $skipInterval) { Text("10 seconds").tag(SkipInterval.ten) Text("15 seconds").tag(SkipInterval.fifteen) } ``` ## Letting ForEach write the tags Listing every case by hand does not scale, so the usual pattern makes the enum **`CaseIterable`** and **`Identifiable`** and loops with `ForEach(SkipInterval.allCases)`. A `ForEach` automatically tags each row with its element's **`id`**. That only helps when the `id` type is exactly the selection type, which is why the idiom is: ```swift enum SkipInterval: Int, CaseIterable, Identifiable { case ten = 10, fifteen = 15, thirty = 30 var id: Self { self } } ``` If the enum instead declared `var id: Int { rawValue }`, the automatic tags would be `Int` values while the selection is a `SkipInterval`, and no row would match. Apple's Picker documentation calls out this exact case and says to add an explicit `.tag(_:)` when the `id` type differs from the selection type. ## How the controls look depends on where they sit Neither control has one fixed appearance. SwiftUI picks a style from the platform and the container: | Control | Inside a `Form` on iOS | Override with | |---|---|---| | `Toggle` | a row with the label and a switch | `toggleStyle(.switch)` or `toggleStyle(.button)` | | `Picker` | a row with the label and the current value; tapping it offers the choices | `pickerStyle(.segmented)`, `.menu`, `.inline`, `.wheel`, `.navigationLink` | Both style modifiers apply to every matching control in the subtree they wrap, so one `.toggleStyle(.switch)` on a `VStack` styles all the toggles inside it. ## Habits that keep a settings screen honest - **Own the value in one place.** The `@State` (or the observable settings model) is the source of truth; the controls only edit it through bindings. - **Model choices as an enum,** not as strings or magic numbers. The compiler then keeps the tags, the stored value and the switch statements that consume it in step. - **Keep the `id` equal to the case** when the enum feeds a picker, or tag explicitly. - **Give every control a real title,** even when a style hides it visually: the title also names the control for VoiceOver. ## Mistakes that show up in review - **A `Toggle` aimed at a read-only computed property.** It has no `$` projection to pass; bind a stored property, or build a `Binding(get:set:)` deliberately. - **Tags on the wrong view.** `.tag(_:)` belongs on each row view inside the picker's content, not on the `Picker` itself. - **An initial selection that matches no row.** If the state starts at a value no tag equals, the picker shows nothing selected until the user chooses. - **Rebuilding the option list from strings.** Renaming a label then silently changes the stored value; an enum case keeps its identity when its display text changes. ## Where this sits This is the junior baseline for every settings screen in SwiftUI. What goes wrong when a tag's type quietly differs from the selection's, how a `Form` restyles each control, and how a screen validates its input before it saves are separate, deeper questions.

  • Why does the enum declare var id: Self { self } rather than using its raw value as the id?
    A `ForEach` tags each row with its element's `id`. The picker's selection is the enum, so the tags must be enum values too. With `var id: Int { rawValue }` the automatic tags would be `Int`s that never equal a `SkipInterval`, and no row would be selected or selectable until you add explicit `.tag(_:)` calls.
  • How do you show a Toggle as a tappable button instead of a switch?
    Apply `toggleStyle(.button)` to the toggle or to a container around it. The button style draws the toggle as a button whose appearance shows the on state. It is available from iOS 15; `toggleStyle(.switch)` forces the switch look, and the automatic style lets SwiftUI choose by platform and context.

  • Passing a plain Bool to Toggle's isOn instead of a binding
  • Expecting a Picker to match rows by their visible text
  • Using the raw value as the id and leaving the rows untagged
  • Storing the picker choice as a free-form String instead of an enum
  • Believing a Toggle looks the same in every container
open as a page

In SwiftUI, how do you respond to taps with onTapGesture, and when should a Button replace the tap gesture?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Attach onTapGesture(count:perform:) to a view to run code on a tap, or on a double tap with count: 2. When the view behaves like a button, use Button instead: it brings the standard button behaviour and accessibility users expect.

open as a page

In SwiftUI, how do you configure TextField and SecureField for a checkout sign-in's email and password so the keyboard and AutoFill fit each field?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Bind a TextField and a SecureField to String state, then describe each field: keyboardType(.emailAddress), textContentType(.username), textInputAutocapitalization(.never) and autocorrectionDisabled() on the email, and textContentType(.password) on the SecureField so AutoFill can help.

open as a page

In SwiftUI, how does putting controls inside a Form with Sections change how they look on iOS, and how do you override that?

level: middleimportance: must knowfreq 62%

basics

~20 s

Form applies platform styling to the controls inside it: on iOS it is a grouped list where each Toggle, Picker, DatePicker and Button becomes a row. Override per control or subtree with pickerStyle, toggleStyle, datePickerStyle, formStyle and controlSize.

open as a page

In SwiftUI, how do you keep a sign-up Form's Create button disabled until the form is valid, and show inline validation messages?

level: middleimportance: must knowfreq 68%

basics

~20 s

Compute validity from the form's state in a computed property, apply .disabled(!isValid) to the Create button only, and show each message conditionally next to its control or in its Section footer, once the user has entered something.

open as a page

In SwiftUI, why keep a DragGesture's live offset in @GestureState rather than @State, and what happens when the drag is cancelled?

level: middleimportance: must knowfreq 65%

basics

~20 s

@GestureState holds a value only while the gesture is active and resets by itself when the gesture ends or is cancelled. Write it in updating(_:body:); commit the final translation to @State in onEnded, which runs only on success.

open as a page

In a SwiftUI checkout address form, how do you use @FocusState with an enum so the keyboard's Next key moves focus through the fields?

level: middleimportance: must knowfreq 78%

basics

~20 s

Declare @FocusState var focus: Field? over a Hashable enum, mark each field with focused($focus, equals:), give them submitLabel(.next), and in one onSubmit assign the next case; setting nil on the last field dismisses the keyboard.

open as a page

In SwiftUI, how do you make a custom model type draggable into other apps and droppable back, using the Transferable protocol?

level: middleimportance: must knowfreq 62%

basics

~20 s

Conform the model to Transferable with a static transferRepresentation, such as a CodableRepresentation under a custom exported UTType plus a ProxyRepresentation to String. Then add draggable(card) to the source view and dropDestination(for: MoodCard.self) to the target.

open as a page

In SwiftUI, a photo card's tap handler either swallows taps on a heart icon inside it or never fires; how do gesture, highPriorityGesture and simultaneousGesture decide which runs?

level: seniorimportance: must knowfreq 58%

basics

~20 s

gesture(:) gives the card's gesture lower precedence than gestures its subviews define, so the heart wins; highPriorityGesture(:) makes the card win, so the heart never fires; simultaneousGesture(_:) runs both. A GestureMask or isEnabled narrows which gestures stay active.

open as a page

In SwiftUI, what does giving a Button a role such as .destructive or .cancel change, and what does it leave to you?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A ButtonRole tells SwiftUI what a button is for, so the system styles and places it per context: destructive draws red in menus, cancel takes a dialog's dismiss slot. It never adds confirmation or changes the action.

open as a page

In SwiftUI, how do you bound a Slider, a Stepper and a DatePicker on a settings screen, and what value types does each accept?

level: middleimportance: should knowfreq 48%

basics

~20 s

Slider binds a floating-point value within in: and an optional step; Stepper binds any Strideable value, Int included, with in: and step:; DatePicker binds a Date and takes a closed or one-sided date range plus displayedComponents.

open as a page

In SwiftUI, how do you let users pinch to zoom and twist to rotate a photo at the same time with MagnifyGesture and RotateGesture?

level: middleimportance: should knowfreq 45%

basics

~10 s

Combine them as MagnifyGesture().simultaneously(with: RotateGesture()), read value.first?.magnification and value.second?.rotation into @GestureState while the fingers move, and in onEnded multiply the committed scale and add the angle into @State. Both types need iOS 17.

open as a page

In SwiftUI, how do simultaneously(with:), sequenced(before:) and exclusively(before:) differ when you combine two gestures on one view?

level: middleimportance: should knowfreq 55%

basics

~20 s

simultaneously(with:) recognises both gestures at once; sequenced(before:) needs the first to succeed before the second starts; exclusively(before:) lets only one succeed, preferring the first, which is how a double tap and a single tap share a view.

open as a page

In SwiftUI, how do you dismiss the software keyboard from a scrolling checkout form, and what does scrollDismissesKeyboard change?

level: middleimportance: should knowfreq 58%

basics

~10 s

Remove focus: set the @FocusState value to nil or false from onSubmit, a button or a keyboard toolbar item. scrollDismissesKeyboard(_:) (iOS 16) chooses whether scrolling dismisses it: immediately, interactively, never or automatic.

open as a page

In SwiftUI, when do you use a TextField with axis: .vertical instead of a TextEditor for a delivery-notes box that grows as the user types?

level: middleimportance: should knowfreq 40%

basics

~10 s

Use TextField(_:text:prompt:axis: .vertical) with lineLimit(2...5) for a short note that should grow and keep a placeholder; use TextEditor for long-form or, from iOS 26, styled AttributedString text in a sized, scrollable area.

open as a page

In SwiftUI, how does dropDestination deliver dropped Transferable items, and what does the DropSession-based variant added in iOS 26 change?

level: middleimportance: should knowfreq 40%

basics

~20 s

dropDestination(for: T.self) builds an array of T from the dropped content through T's import representations. The iOS 16 form also passes the drop location, returns a Bool and reports hover through isTargeted; iOS 26's dropDestination(for:isEnabled:action:) passes a DropSession instead.

open as a page

In Core Transferable, how do you choose among CodableRepresentation, DataRepresentation, FileRepresentation and ProxyRepresentation, and why does their order matter?

level: middleimportance: should knowfreq 45%

basics

~20 s

Use CodableRepresentation for a Codable model, DataRepresentation for in-memory bytes, FileRepresentation for large content on disk and ProxyRepresentation to reuse another Transferable type. List the most faithful first: earlier entries are preferred, later ones are compatible fallbacks.

open as a page

A SwiftUI sleep-timer Picker bound to a Double shows no selection and ignores taps, though every row has a tag; why, and how do you fix it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Each .tag(15) infers an Int tag, but the Picker looks for tags of its selection type, Double, so no row matches. Tag with the same type, such as .tag(15.0), or model the choices as an enum.

open as a page

A SwiftUI checkout form binds its postcode TextField to an Int with format: .number; why does it lag behind typing and drop leading zeros, and what do you use instead?

level: seniorimportance: should knowfreq 42%

basics

~10 s

A value-bound TextField writes the Int only when the edit is committed, and an Int cannot keep leading zeros or letters. Bind a String, use keyboardType(.numberPad) and textContentType(.postalCode), and filter to digits in onChange(of:).

open as a page

In a SwiftUI mood-board app, cards drag between its own screens, but dropping one into Notes does nothing and text dragged from Notes never lands; why?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Notes can't read the card's custom content type and no common fallback is offered; text can't become a card because nothing imports String. Add a two-way ProxyRepresentation to String, and declare the custom type in Info.plist conforming to public.data.

open as a page

In a SwiftUI board that imports dropped photos through FileRepresentation, saved photo URLs later point to missing files; why, and how do you fix it?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

FileRepresentation's importing closure gets a ReceivedTransferredFile whose file is only guaranteed to exist while that closure runs. Storing received.file keeps a URL that can dangle; copy the file into the app's own container inside the closure and keep the copy's URL.

open as a page