Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 46 ยท Views and Layout

Buttons, Toggles, Sliders and Pickers

Learn the core SwiftUI controls: Button, Toggle, Slider, Stepper, Picker, DatePicker, Menu and ControlGroup, with button roles, styles and accessibility basics.

Controls turn a screen from a picture into something you can use. SwiftUI ships a small set of them that cover most input: a Button performs an action, a Toggle flips a Boolean, a Slider or Stepper adjusts a number, a Picker chooses one of several values, and a DatePicker chooses a date. Each draws itself in the platform's native style, so the same code looks right on iPhone, iPad and Mac.

Value controls do not own their value. They are handed a binding, a two-way connection to a piece of state stored elsewhere, and write the new value through it. That is covered fully in @State and @Binding; for now, read $volume as "a read-write connection to volume". SwiftUI code is read-only on this site, so the runnable examples model the logic behind the controls in plain Swift.

One control per kind of input

Button Run an action.
Toggle On or off.
Slider, Stepper Adjust a number.
Picker Choose one option.

Value controls write through a binding.

1 / 2

Button

A button takes an action closure and a label. The shortest form uses a title string:

Swift
Button("Save") {
    save()
}

When the label needs more than text, use the second initializer, where the label is a view:

Swift
Button {
    addToFavorites()
} label: {
    Label("Favorite", systemImage: "heart")
}

The role parameter gives a button meaning. .destructive draws it in red where the context allows, and .cancel places it where users expect a cancel action in alerts and dialogs. A style modifier chooses the look:

Swift
Button("Delete account", role: .destructive) {
    showConfirmation = true
}

Button("Continue") { next() }
    .buttonStyle(.borderedProminent)
    .controlSize(.large)

Common styles are .automatic, .plain, .bordered and .borderedProminent. The style is applied to the whole subtree, so putting .buttonStyle on a container restyles every button inside it.

The action closure runs on the main actor and should return quickly. For slow work, start an asynchronous task inside it, as shown in later lessons, so the interface stays responsive.

Toggle, Slider and Stepper

A Toggle shows a label and a switch bound to a Bool:

Swift
Toggle("Notifications", isOn: $notificationsOn)

A Slider binds to a floating-point value inside a range, and can snap to steps:

Swift
Slider(value: $volume, in: 0...1)
Slider(value: $rating, in: 0...5, step: 0.5)

A Stepper has minus and plus buttons and works well for small integer counts. It accepts a label view, so you can show the current value in the label:

Swift
Stepper("Guests: \(guests)", value: $guests, in: 1...10)

The Slider and Stepper both clamp into their range, and the Stepper disables the button that would leave it. This model captures that behaviour, and also the snapping a stepped slider does.

Swift Clamping and snapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Picker

A Picker chooses one value from several. Each option is a view with a .tag(_:) that supplies the value to write into the binding when that option is picked:

Swift
enum Roast: String, CaseIterable, Identifiable {
    case light, medium, dark
    var id: Self { self }
}

Picker("Roast", selection: $roast) {
    ForEach(Roast.allCases) { roast in
        Text(roast.rawValue.capitalized).tag(roast)
    }
}

The look depends on .pickerStyle: .menu (a button that opens a menu), .segmented (a compact bar for two to four options), .inline, and .wheel. In a Form or List the default is often a row that navigates or opens a menu.

The most common Picker bug is a type mismatch between the selection and the tags. If selection is an optional (Roast?) but the tags are plain Roast values, no tag equals the selection, and the picker shows nothing selected. Make them the same type, or tag with Roast?.some(roast).

Swift Why a tag must match the selection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

DatePicker, Menu and ControlGroup

DatePicker binds to a Date. You choose what to ask for with displayedComponents and can constrain the allowed range:

Swift
DatePicker("Due", selection: $dueDate, in: Date.now..., displayedComponents: [.date, .hourAndMinute])

A Menu shows a button that reveals a list of actions. Items are ordinary Buttons, and you can nest menus or place a Picker inside one:

Swift
Menu("Sort") {
    Button("Name") { sortKey = .name }
    Button("Date") { sortKey = .date }
    Button("Delete all", role: .destructive) { deleteAll() }
}

ControlGroup visually groups related controls, such as a row of buttons that act as one cluster in a toolbar or menu:

Swift
ControlGroup {
    Button("Cut") { }
    Button("Copy") { }
    Button("Paste") { }
}

Accessibility basics

Native controls are accessible by default: a button announces itself as a button, and a toggle reports its on or off state. Your job is to give them good labels. A button that shows only an icon has no readable name until you add one:

Swift
Button {
    share()
} label: {
    Image(systemName: "square.and.arrow.up")
}
.accessibilityLabel("Share")
.accessibilityHint("Opens the share sheet")

A Label("Share", systemImage: ...) gives VoiceOver the text for free. Use .accessibilityValue to expose a number with meaning, such as "60 percent" for a slider, and .accessibilityAddTraits(.isButton) when a tappable view is not a real Button. Prefer a real Button, though, because it also gives you keyboard, switch-control and pointer support without extra work.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a role of .destructive on a Button change?

    Roles give the button meaning. A destructive button is drawn in a warning style (red where the context allows), and a cancel button is placed where users expect it.
  2. 2. Which control is the best fit for choosing a number between 0 and 1 by dragging?

    A Slider binds to a floating-point value in a range. A Stepper suits small whole-number counts.
  3. 3. A Picker shows nothing selected. The selection is Roast? and the tags are plain Roast values. Why?

    A Picker matches the selection against the tags by type and value. Make both optional or both non-optional.
  4. 4. How should an icon-only button be made accessible?

    An image alone has no meaningful name for VoiceOver. A label such as "Share" tells users what the button does.

Summary

  • Button runs an action; roles (.destructive, .cancel) and styles (.bordered, .borderedProminent) give it meaning and look.
  • Toggle, Slider, Stepper, Picker and DatePicker edit a value through a binding ($name).
  • Slider and Stepper clamp to their range; a stepped Slider snaps to the nearest step.
  • A Picker's selection and its tags must have the same type, or nothing appears selected.
  • Menu and ControlGroup organize actions; give icon-only controls an accessibility label.

Next, learn what those bindings really are in @State and @Binding.