In SwiftUI, how do you bound a Slider, a Stepper and a DatePicker on a settings screen, and what value types does each accept?
answer
- each control has its own range type
- Slider is floating point only
- Stepper strides over integers too
- partial date ranges exist
- commit on editing end
basics
~20 sSlider 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.
solid answer
~30 s`Slider(value:in:step:)` requires a `BinaryFloatingPoint` value such as `Double`, defaults to `0...1`, and snaps to `step`; its `onEditingChanged` closure reports `true` when a drag starts and `false` when it ends, which is the moment to persist an expensive change. `Stepper(value:in:step:)` accepts any `Strideable`, so an `Int` episode limit works, and `onIncrement`/`onDecrement` give full control when the next value is not simple arithmetic. `DatePicker` binds a `Date`, accepts `in:` as a `ClosedRange<Date>`, a `PartialRangeFrom` such as `Date.now...` or a `PartialRangeThrough`, and `displayedComponents` defaults to `[.hourAndMinute, .date]`. The ranges limit what the user can pick; values from elsewhere still need your own validation.
code
swift · 24 linesimport SwiftUI
struct PlaybackControls: View {
@State private var speed = 1.0
@State private var episodeLimit = 5
@State private var reminder = Date.now
let saveSpeed: (Double) -> Void
var body: some View {
Form {
LabeledContent("Speed", value: speed, format: .number.precision(.fractionLength(2)))
Slider(value: $speed, in: 0.5...3.0, step: 0.25) {
Text("Playback speed")
} onEditingChanged: { editing in
if !editing { saveSpeed(speed) }
}
Stepper("Keep \(episodeLimit) episodes", value: $episodeLimit, in: 1...50)
DatePicker("Remind me",
selection: $reminder,
in: Date.now...,
displayedComponents: [.date, .hourAndMinute])
}
}
}go deeper
Recall which control binds which type: Slider for floating point, Stepper for counts, DatePicker for Date, each with an in: range.
Explain step, onEditingChanged, the one-sided date ranges and the displayedComponents default, and why an Int slider will not compile.
Show that you persist on editing end, derive dependent ranges from state, and validate values arriving from storage or sync rather than trusting the control.
Discuss choosing controls and ranges as product rules shared with the backend, so limits change in one place across clients.
## Three controls, three value models A podcast app's settings screen needs a playback **speed**, an **episode limit** and a **reminder** time. SwiftUI offers a different control for each, and each one constrains its value differently. Getting the type wrong is a compile error; getting the range wrong lets users pick nonsense. | Control | Bound type | Range parameter | Granularity | |---|---|---|---| | `Slider` | `BinaryFloatingPoint` (`Double`, `Float`, `CGFloat`) | `in: ClosedRange<V>`, default `0...1` | optional `step:` | | `Stepper` | any `Strideable` (`Int`, `Double`, ...) | optional `in: ClosedRange<V>` | `step:`, default `1` | | `DatePicker` | `Date` | `in:` as `ClosedRange`, `PartialRangeFrom` or `PartialRangeThrough` | `displayedComponents:` | ## Slider: continuous values `Slider` binds to a floating-point value. The generic constraint is `V : BinaryFloatingPoint` with a floating-point `Stride`, so binding an `Int` fails to compile with an error that `Int` does not conform to `BinaryFloatingPoint`. For speed that is fine: ```swift Slider(value: $speed, in: 0.5...3.0, step: 0.25) { Text("Playback speed") } onEditingChanged: { editing in if !editing { saveSpeed(speed) } } ``` - **`step:`** makes the thumb move in increments; Apple's documentation adds that the step is also used when a VoiceOver user adjusts the slider with voice commands. - **`onEditingChanged`** is called with `true` when interaction starts and `false` when it ends. The binding updates continuously during a drag, so persist or send network requests on `false`, not from every change. - **Minimum and maximum value labels** are available through the initialisers that take `minimumValueLabel:` and `maximumValueLabel:`. - Show the current value yourself — for example with a `LabeledContent` row above the slider. ## Stepper: discrete values `Stepper` binds to any `Strideable` value, which is why it is the natural choice for whole numbers: ```swift Stepper("Keep \(episodeLimit) episodes", value: $episodeLimit, in: 1...50) ``` - **`in:`** bounds the value and **`step:`** sets the increment. - **`Stepper(label:onIncrement:onDecrement:)`** hands you the two taps when the next value is not plain arithmetic — Apple's example wraps around an array of colours. - **`format:`** initialisers (iOS 16) display a floating-point value through a `ParseableFormatStyle`. ## DatePicker: dates and times `DatePicker` binds to a `Date`. Two parameters matter: 1. **`in:`** — a `ClosedRange<Date>` for a window, `Date.now...` (a `PartialRangeFrom`) for "only in the future", or `...Date.now` (a `PartialRangeThrough`) for "only in the past", such as a birthday. 2. **`displayedComponents:`** — `.date`, `.hourAndMinute` or both. The default is `[.hourAndMinute, .date]`, so a birthday picker that omits it also asks for a time. Style it with `datePickerStyle(.compact)`, `.graphical` or `.wheel`. On iOS the basic picker shows the date as text and opens a calendar when tapped. ## Ranges are input limits, not model rules A control's range limits what the **user** can choose through that control. It does not validate the value your model receives from elsewhere: a default restored from storage, a value synced from another device, or a migration from an older range. Validate or clamp those where they enter the model. When a range depends on other state — a reminder that must fall before an episode's release — compute it from that state, so the control and the rule cannot drift apart. ## Mistakes to avoid - **Binding an `Int` to a `Slider`** and then reaching for a cast inside `body`; convert in a dedicated binding or use a `Stepper`. - **Leaving `displayedComponents` at its default** on a date-only field such as a birthday, which then asks for a time as well. - **A step that does not divide the range,** such as `0.5...3.0` with `step: 0.4`, whose steps (0.5, 0.9, ... 2.9) never land exactly on the maximum. - **Hiding the current value.** A slider with no visible number gives the user no way to hit 1.25 exactly. - **Writing on every change.** Persist on the end of editing, or debounce, rather than on each frame of a drag. ## Choosing between them - **Slider** for approximate continuous values where the user cares about feel (speed, volume). - **Stepper** for small exact counts (episode limit, copies), and anywhere an `Int` must stay an `Int`. - **DatePicker** for dates and times, with the narrowest components and range that fit. Picking the right control and range up front removes most validation from the screen before any message is needed.
- How do you drive an Int setting with a Slider when the design insists on one?Bind the slider to a `Binding<Double>` built with `Binding(get:set:)` that converts to and from the `Int`, and pass `step: 1` so the thumb lands on whole numbers. Better still, ask whether a `Stepper` fits: it binds the `Int` directly and makes exact values easier to hit.
- Why is saving the speed inside onChange(of: speed) worse than saving in onEditingChanged?The binding changes on every frame of a drag, so `onChange(of:)` fires many times and each call would write storage or hit the network. `onEditingChanged` reports `false` once, when the user lets go, which is the single moment the chosen value is final.
- A Slider can bind directly to an Int
- displayedComponents defaults to date only
- A DatePicker range must always be a closed range
- The control's range validates every value in the model
- Saving on every slider change is free