In Swift Charts, how do you show a year of daily step totals as a horizontally scrolling chart that opens on the latest week?
answer
- scrolling is a chart modifier
- how much fits on screen
- seconds on a date axis
- an initial scroll position
- snap with value alignment
basics
~10 sFrom iOS 17, add chartScrollableAxes(.horizontal), set chartXVisibleDomain(length:) to one week in seconds, open with chartScrollPosition(initialX:) at the latest week's start, and snap with chartScrollTargetBehavior(.valueAligned(matching:)).
solid answer
~40 sWrapping a `Chart` in a SwiftUI `ScrollView` scrolls the whole view, axes included, so Swift Charts has its own modifiers from iOS 17. `chartScrollableAxes(.horizontal)` lets the plot scroll while the y-axis stays put. `chartXVisibleDomain(length:)` decides how much of the x domain is on screen; it takes a `Numeric` value, so for a `Date` axis you pass seconds, `3600 * 24 * 7` for a week, and passing a `Date` does not compile. `chartScrollPosition(initialX:)` sets where the visible window sits when the chart appears, and `chartScrollPosition(x:)` binds it so you can read it, for example to show the week's total. `chartScrollTargetBehavior(.valueAligned(matching: DateComponents(hour: 0)))` makes scrolling settle on midnight. Daily labels come from `chartXAxis { AxisMarks(values: .stride(by: .day)) }`.
code
swift · 38 linesimport SwiftUI
import Charts
struct DailySteps: Identifiable {
let id = UUID()
let day: Date
let steps: Int
}
struct YearOfStepsChart: View {
let days: [DailySteps] // a year of daily totals, oldest first
private var lastWeekStart: Date {
let newest = days.last?.day ?? .now
return Calendar.current.date(byAdding: .day, value: -6, to: newest) ?? newest
}
var body: some View {
Chart(days) { entry in
BarMark(
x: .value("Day", entry.day, unit: .day),
y: .value("Steps", entry.steps)
)
}
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: 3600 * 24 * 7) // seconds: one week on screen
.chartScrollPosition(initialX: lastWeekStart)
.chartScrollTargetBehavior(
.valueAligned(matching: DateComponents(hour: 0)) // settle on midnight
)
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { _ in
AxisGridLine()
AxisValueLabel(format: .dateTime.weekday(.abbreviated), centered: true)
}
}
}
}go deeper
Recall that iOS 17 charts scroll with chartScrollableAxes and that chartXVisibleDomain(length:) sets how much is on screen.
Explain why the visible length on a date axis is in seconds, and how initial and bound scroll positions differ.
Build a year-long scrolling chart that opens on the newest week, snaps to days and reports what is visible, and explain why a ScrollView is the wrong tool.
Decide between scrolling and paginated or aggregated views for long histories, given what readers compare and what the deployment target allows.
## Why not a `ScrollView` A year of daily bars cannot fit on a phone, so the chart has to scroll. Wrapping the `Chart` in a SwiftUI `ScrollView(.horizontal)` and giving it a wide frame scrolls the whole view: the y-axis labels scroll away with the bars, and the chart knows nothing about the scroll, so it cannot snap to days or report which week is showing. **iOS 17** added scrolling to Swift Charts itself. ## The scrolling modifiers | Modifier | Role | |---|---| | `chartScrollableAxes(_:)` | turns on scrolling along `.horizontal`, `.vertical` or both | | `chartXVisibleDomain(length:)` | how much of the x domain is visible at once | | `chartScrollPosition(initialX:)` | where the visible window sits when the chart appears | | `chartScrollPosition(x:)` | a binding to that position, read and written by you | | `chartScrollTargetBehavior(_:)` | where scrolling comes to rest | All five are declared on `View` with iOS 17 availability, beside y-axis versions of the visible-domain and position modifiers. ## How much is visible `chartXVisibleDomain(length:)` is generic over a type that is both `Plottable` and `Numeric`. On a numeric axis you pass the span in the axis's own units. On a `Date` axis you cannot pass a `Date`; the compiler reports that 'Date' must conform to 'Numeric'. The length is a number of **seconds**: - one day: `3600 * 24`; - one week: `3600 * 24 * 7`; - thirty days: `3600 * 24 * 30`. Set the visible length explicitly whenever you make an axis scrollable: it is the value that makes the plot wider than the screen. ## Where the window starts To open on the newest data, set `chartScrollPosition(initialX:)` with the date at the start of the window you want first on screen, here six days before the latest entry so seven days show. When the screen needs to know what is visible, for example to show "Week of 6 October: 61,204 steps" above the plot, bind `chartScrollPosition(x:)` to `@State` instead and compute the visible range from it and the visible length. ## Snapping Without a target behaviour, scrolling can come to rest anywhere, often mid-bar. `chartScrollTargetBehavior(_:)` takes a `ChartScrollTargetBehavior`; Swift Charts ships `ValueAlignedChartScrollTargetBehavior`, created with: 1. `.valueAligned(unit:)` for numeric axes, for example `unit: 10`; 2. `.valueAligned(matching:)` for dates, for example `DateComponents(hour: 0)` to rest on midnight; 3. an optional `majorAlignment:`, such as `.page` or `.matching(DateComponents(weekday: 2))`, that makes a swipe jump to the next major unit. Apple's documentation says that when the user finishes a scroll gesture the chart "will snap to align to the given unit or the end of the domain". ## Date axis marks Scrolling a week at a time reads best with one label per day. Configure the axis with `AxisMarks`: ```swift .chartXAxis { AxisMarks(values: .stride(by: .day)) { _ in AxisGridLine() AxisValueLabel(format: .dateTime.weekday(.abbreviated), centered: true) } } ``` `.stride(by:count:)` takes a `Calendar.Component`, so `.stride(by: .day)` marks every day. `AxisValueLabel(format:centered:)` formats each date, and `centered: true` puts the label in the middle of the day's slot, under its bar, instead of at the boundary. ## Long histories on iOS 18 and later A year of daily bars is a few hundred marks, which `ForEach` handles. For much larger series, such as minute-by-minute heart rate over months, iOS 18 added **vectorized plots**: `BarPlot`, `LinePlot`, `AreaPlot`, `PointPlot`, `RulePlot`, `RectanglePlot` and `SectorPlot`. They take the whole collection and key paths instead of one mark per element: ```swift Chart { BarPlot(days, x: .value("Day", \.day), y: .value("Steps", \.steps)) } ``` Here `.value` builds a `PlottableProjection` from a key path rather than a `PlottableValue` from a value. The scrolling, visible-domain and axis modifiers above are view modifiers on the chart, so they apply in the same way whichever kind of content it holds. ## Common mistakes 1. Wrapping the chart in a `ScrollView`, losing the fixed y-axis. 2. Turning on `chartScrollableAxes` without a visible domain length. 3. Passing a day count where the date axis expects seconds, which shows seven seconds of data. 4. Expecting `SwiftUI.scrollTargetBehavior(_:)`, the `ScrollView` modifier, to snap a chart. 5. Forgetting that these modifiers need iOS 17, so an iOS 16 target needs an availability check or a paged fallback.
- In Swift Charts, how do you make a swipe on the scrolling step chart jump a whole week at a time?Add a major alignment: `.valueAligned(matching: DateComponents(hour: 0), majorAlignment: .page)`. Slow drags still settle on a midnight, while a swipe moves to the next or previous major unit, here a page, which is the visible week.
- In Swift Charts, how do you show the total for the week currently in view?Bind `chartScrollPosition(x:)` to a `@State` `Date`, compute the visible interval as that date plus the visible length in seconds, and sum the entries whose day falls inside it. The header updates as the binding changes while the user scrolls.
- Wrapping the Chart in a ScrollView is the standard way to scroll it
- chartXVisibleDomain(length: 7) shows seven days on a Date axis
- chartXVisibleDomain takes a Date length on a date axis
- scrollTargetBehavior(.viewAligned) snaps a scrolling chart
- Chart scrolling works on iOS 16
Assumes the iOS 27 SDK; chartScrollableAxes, chartXVisibleDomain, chartScrollPosition and chartScrollTargetBehavior arrived in iOS 17.