How it works
SliderTickContentForEach is the view that SwiftUI constructs when you supply tick marks to a Slider through a ForEach, gathering each per-element SliderTick into a single piece of tick content the slider can lay out along its track. It exists so you can describe a slider's discrete stops programmatically — one tick per item in a collection — rather than spelling out every mark by hand. Reach for it whenever the number or position of ticks is driven by data or a range, such as a fixed set of rating steps, and you want each value in that range to render as its own visible snap target.
Open a tick-content builder on Slider
A slider gains discrete marks through a trailing
ticks:builder closure, distinct from the label closure. Here theSlider(value:in:step:)call pairs aText("Rating")label with aticks:block, and everything you return inside that block becomes the slider's tick content.Drive the ticks with ForEach
When you place a
ForEachinside theticks:builder, SwiftUI wraps the iterated marks inSliderTickContentForEachso the whole sequence behaves as one tick-content value. The example iteratesForEach(0...8, id: \.self), producing one tick for every integer rating from 0 through 8.Emit a SliderTick per element
The body of the
ForEachreturns the actual mark for each element — aSliderTickpositioned at a value on the slider's scale. For each indexi, the example yieldsSliderTick(Double(i)), placing a tick at that exact rating;SliderTickContentForEachcollects them and hands the assembled set to the slider.Keep ticks aligned to the value range and step
Because each
SliderTickis positioned by an explicit value, your tick values should match the slider's domain so the marks line up with where the thumb can land. Thein: 0...8, step: 1configuration mirrors the0...8range driving theForEach, so every snap position the slider allows has a corresponding tick.
ForEach(0...8, id: \.self) to ForEach(stride(from: 0, through: 8, by: 2).map { $0 }, id: \.self) so only even ratings emit a SliderTick, and watch the slider draw marks at half as many positions.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 SliderTickContentForEachDemo: View {
@State private var value = 4.0
var body: some View {
VStack(spacing: 16) {
Text("Rating: \(Int(value))")
.font(.headline)
Slider(value: $value, in: 0...8, step: 1) {
Text("Rating")
} ticks: {
ForEach(0...8, id: \.self) { i in
SliderTick(Double(i))
}
}
}
.padding()
}
}