In Swift Charts on iOS 17 and later, how do you let a user scrub a heart-rate line chart with a finger and mark the selected sample?
answer
- a binding, not a gesture
- the value under the finger
- find the nearest sample
- conditional RuleMark in the builder
- ChartProxy before iOS 17
basics
~20 sBind chartXSelection(value:) to an optional Date; the chart writes the x value under the finger, you look up the nearest sample, and an if let in the Chart builder draws a RuleMark(x:) with an annotation for the reading.
solid answer
~40 sFrom iOS 17, `.chartXSelection(value: $rawSelection)` takes a `Binding<P?>` where `P` is the x data type, here `Date?`. While the user interacts, the chart writes the x value under the finger into the binding, and `nil` means nothing is selected. It is a raw value on the axis, not one of your elements, so compute the nearest `HeartRateSample` yourself. Inside the `Chart` builder, `if let selected { RuleMark(x: .value("Selected", selected.time)) }` draws the indicator, and `.annotation(position: .top, overflowResolution: .init(x: .fit, y: .disabled))` shows the bpm without spilling off the plot. `chartXSelection(range:)` selects an interval instead. Before iOS 17 you built this by hand: a `chartOverlay` with a `DragGesture`, converting the touch to a value with `ChartProxy.value(atX:as:)`.
code
swift · 36 linesimport SwiftUI
import Charts
struct HeartRateSample: Identifiable {
let id = UUID()
let time: Date
let bpm: Double
}
struct HeartRateChart: View {
let samples: [HeartRateSample]
@State private var rawSelection: Date?
private var selected: HeartRateSample? {
guard let rawSelection else { return nil }
return samples.min {
abs($0.time.timeIntervalSince(rawSelection)) < abs($1.time.timeIntervalSince(rawSelection))
}
}
var body: some View {
Chart {
ForEach(samples) { sample in
LineMark(x: .value("Time", sample.time), y: .value("BPM", sample.bpm))
}
if let selected {
RuleMark(x: .value("Selected", selected.time))
.foregroundStyle(.gray.opacity(0.4))
.annotation(position: .top, overflowResolution: .init(x: .fit, y: .disabled)) {
Text("\(Int(selected.bpm)) bpm").font(.caption.bold())
}
}
}
.chartXSelection(value: $rawSelection)
}
}go deeper
Recall that iOS 17 added chartXSelection(value:), bound to optional state of the x value's type, and that a RuleMark can mark the selection.
Explain what the binding holds, why you resolve it to the nearest element yourself, and how an if let inside the Chart builder draws the indicator.
Build the iOS 16 fallback with chartOverlay and ChartProxy, keep annotations inside the plot, and make values reachable for VoiceOver users too.
Weigh dropping iOS 16 to replace hand-written overlay gestures with the selection modifiers, and set one interaction pattern for every chart in the app.
## The selection modifiers Until iOS 17, Swift Charts had no built-in selection: you read touches yourself. **iOS 17** added selection as view modifiers on the chart, each bound to a piece of your state: | Modifier | Binding | Selects | |---|---|---| | `chartXSelection(value:)` | `Binding<P?>` | one x value | | `chartXSelection(range:)` | `Binding<ClosedRange<P>?>` | an x interval | | `chartYSelection(value:)` / `(range:)` | same shapes | along y | | `chartAngleSelection(value:)` | `Binding<P?>` | a value on a sector chart's angle | `P` must be `Plottable`. For a heart-rate chart whose x values are `Date`s, the state is `@State private var rawSelection: Date?`. ## What the binding receives The binding's type is the axis's value type, not your element type, and that shapes the code: - it holds a `Date` on the x scale, wherever the finger is, so it rarely equals a sample's timestamp exactly; - `nil` means there is no selection, and your UI should hide the indicator then; - the chart writes it; you only read it, plus set it if you want to clear or preset a selection. So you resolve the raw value into data: for time series, the sample with the smallest time difference; for daily bars, the element whose day contains the date. Keep that lookup in a computed property so the view stays declarative. ## Drawing the rule and the readout Chart content builders accept `if` statements, so the indicator is ordinary content: ```swift if let selected { RuleMark(x: .value("Selected", selected.time)) .foregroundStyle(.gray.opacity(0.4)) .annotation(position: .top, overflowResolution: .init(x: .fit, y: .disabled)) { Text("\(Int(selected.bpm)) bpm") } } ``` `RuleMark(x:)` with no `yStart` or `yEnd` spans the plot vertically. The `overflowResolution:` parameter, an `AnnotationOverflowResolution` added in iOS 17, decides what happens when the label would leave the chart: `.fit` keeps it inside along x, and `.disabled` turns that resolution off along y. You can add a `PointMark` at the selected sample to emphasise the exact reading. ## Before iOS 17: `chartOverlay` and `ChartProxy` Apps that support iOS 16 build the same interaction by hand: 1. Add `.chartOverlay { proxy in GeometryReader { geo in ... } }` with a clear, hit-testable `Rectangle`. 2. Attach a `DragGesture(minimumDistance: 0)` and, in `onChanged`, convert the touch from the overlay's space into the plot's space using the plot frame. On iOS 17 that is `proxy.plotFrame`; the older `plotAreaFrame` is deprecated in iOS 17 and renamed to it. 3. Call `proxy.value(atX: x, as: Date.self)` to turn a horizontal position into a data value, and clear the state in `onEnded`. `ChartProxy` also goes the other way: `position(forX:)` gives the on-screen position for a value, which is how you place a custom view at a mark. ## Customising the gesture If the default selection gesture conflicts with something else on screen, iOS 17's `chartGesture(_:)` lets you supply your own gesture built from the `ChartProxy` it hands you, and drive selection by calling `proxy.selectXValue(at:)` or `proxy.selectXRange(from:to:)`. The selection binding is then still the single place your view reads from. ## Selecting a range When the question is "what happened during this workout" rather than "what was the reading at 9:41", select an interval. `chartXSelection(range:)` binds a `ClosedRange<P>?`, so for the heart-rate chart the state is `@State private var selectedWindow: ClosedRange<Date>?`. The pattern mirrors single-value selection: - draw the window as chart content, for example `RectangleMark(xStart: .value("Start", window.lowerBound), xEnd: .value("End", window.upperBound))` with a translucent style; - filter the samples whose time falls inside the range; - summarise them, such as the average and peak bpm, in a header above the chart. Because the range is again raw axis values, the same rule applies: the chart reports positions on the scale, and your code decides which data they cover. ## Accessibility Scrubbing is a touch interaction. VoiceOver users reach individual values through the marks' accessibility elements, which you can tune with `accessibilityLabel(_:)` and `accessibilityValue(_:)` on the `LineMark`, so make sure a reading such as "9:41, 72 bpm" is available there and not only in the scrub annotation. ## Common mistakes 1. Typing the binding as the element (`HeartRateSample?`) instead of the axis value type. 2. Expecting the selected value to match a sample exactly. 3. Drawing the rule with an overlay view and manual geometry when a conditional `RuleMark` in the builder does the job. 4. Using `chartXSelection` in an app whose deployment target is iOS 16 without an availability check. 5. Reading `plotAreaFrame` in new code instead of `plotFrame`.
- In Swift Charts, how would you let the user select a time window, say a workout interval, instead of one instant?Bind `chartXSelection(range:)` to a `ClosedRange<Date>?`. The chart writes the selected interval, and you can draw it with a `RectangleMark(xStart:xEnd:)` over the range and summarise the samples it contains, such as the average bpm.
- In Swift Charts, why might you still use chartOverlay in an app whose deployment target is iOS 17?`chartOverlay` hands you a `ChartProxy` and a place to put your own SwiftUI views over the plot, which selection modifiers do not. Use it for a floating callout positioned with `proxy.position(forX:)`, or for interactions other than selection, while still driving selection through the binding.
- chartXSelection hands you the selected data element directly
- The selected Date always equals one of the sample timestamps
- chartXSelection is available on iOS 16 with Swift Charts
- A selection indicator must be an overlay view, not chart content
- plotAreaFrame is still the property to use in new code
Assumes the iOS 27 SDK; chartXSelection, chartGesture, AnnotationOverflowResolution and ChartProxy.plotFrame arrived in iOS 17, and iOS 16 needs chartOverlay with ChartProxy.value(atX:as:).