How it works
A Slider is a control for selecting a value from a bounded, continuous range by dragging a thumb along a track. Reach for it whenever a user should pick an approximate magnitude — volume, brightness, opacity, playback position — where the relative position of the value matters more than typing an exact number. Slider binds directly to your model through a value binding, so the displayed position and your state always stay in sync as the user drags. It is the right tool when the range is known and the choice is one-dimensional.
Drive the slider with a value binding
The core of a Slider is its
valueparameter, a two-wayBindingto aBinaryFloatingPointyou own. The thumb's position reflects that value, and dragging writes the new value straight back through the binding. HereSlider(value: $volume, ...)binds to the@State private var volumeso the control and theText("Volume: \(Int(volume))")label move together.Bound the track with the in: range
The
in:parameter takes aClosedRangethat defines the slider's lowest and highest selectable values, mapping the left edge to the lower bound and the right edge to the upper bound. Within: 0...100, the thumb travels from 0 on the left to 100 on the right, clampingvolumeto that span.Quantize movement with step:
Passing a
step:makes the slider snap to discrete increments instead of moving continuously, so the bound value only ever lands on multiples of that stride. Usingstep: 1over0...100restrictsvolumeto whole numbers, which is whyInt(volume)reads cleanly without fractional jitter.Describe the control with a label
The trailing-closure
labelprovides an accessibility description of what the slider adjusts; it is read by assistive technologies even though it is not drawn on the standard track. SupplyingText("Volume")as the label names the control for VoiceOver users.Anchor the ends with value labels
The
minimumValueLabelandmaximumValueLabelclosures place views at the low and high ends of the track to signal direction and meaning at a glance. HereImage(systemName: "speaker.fill")marks the quiet end andImage(systemName: "speaker.wave.3.fill")marks the loud end, framing the range with icons instead of bare numbers.
step: 1 to step: 25 and drag the thumb — the slider will snap to 0, 25, 50, 75, and 100, showing how the step value quantizes the bound volume.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct SliderDemo: View {
@State private var volume = 50.0
var body: some View {
VStack(spacing: 16) {
Text("Volume: \(Int(volume))")
.font(.headline)
Slider(value: $volume, in: 0...100, step: 1) {
Text("Volume")
} minimumValueLabel: {
Image(systemName: "speaker.fill")
} maximumValueLabel: {
Image(systemName: "speaker.wave.3.fill")
}
}
.padding()
}
}