
Mastering Forms in SwiftUI: Sliders and Steppers
Learn how to use sliders and steppers in forms in SwiftUI apps.
When handling numeric input and output within form interactions using a TextField
with a numeric keyboard associated with it is the first impulse. However, there are use cases where providing a specific component offers a better experience, such as when the numeric value must be within a particular range of values or when the best interaction is to increase or decrease the numeric value gradually. Sliders and steppers are the components for those jobs.
Sliders
A Slider
is a horizontal component that allows users to adjust a numeric value within a specified minimum and maximum range. The user interacts with a “thumb” element that moves along a track that gradually fills up with color.
@State private var temperature = 21.0
var body: some View {
NavigationStack {
Form {
Section("Temperature") {
Text("Temperature: \(temperature, specifier: "%.1f°C")")
Slider(value: $temperature, in: 15...35)
}
}
.navigationTitle("Thermostat")
}
}
Additionally, sliders can optionally display left and right icons that provide a visual representation of the minimum and maximum values.
Slider(value: $temperature) {
Text("Temperature")
} minimumValueLabel: {
Text("15°C")
} maximumValueLabel: {
Text("35°C")
}
Steppers
When getting a numeric input through incrementing or decrementing a value, use a Stepper
. It is the best user experience if you want the user to have granular control over the value.
@State private var numberOfParticipants = 1
var body: some View {
NavigationStack {
Form {
Section("Number of participants") {
Stepper(value: $numberOfParticipants) {
Text("^[\(numberOfParticipants) guest](inflect: true)")
}
}
}
.navigationTitle("Your party")
}
}
A range of values can also be defined for a stepper, limiting how much the value can be incremented or decremented.
Stepper(value: $numberOfParticipants, in: 1...10, step: 1) {
Text("^[\(numberOfParticipants) guest](inflect: true)")
}
It is possible to define specific actions to be performed when the user increments or decrements the stepper. It can be used to perform calculations or validations, for example, when the user changes the value.
Stepper {
Text("^[\(numberOfParticipants) guest](inflect: true)")
} onIncrement: {
numberOfParticipants = numberOfParticipants + 1
} onDecrement: {
numberOfParticipants = numberOfParticipants - 1
}