How can Charts display sales data for a full month and support monthly paging?

Due to the varying number of days in each month, I am unsure how to enable monthly paging in Charts.

In Apple's official example, SwiftChartsExample, there is only an example showing the sales of the "last 30 days":

.chartXVisibleDomain(length: 3600 * 24 * 30)

I have tried using scrollPosition to calculate the number of days in the current month, like this:

var days: Int {
    let current = Calendar.current
    let dateRange = current.range(of: .day, in: .month, for: scrollPosition)
    return dateRange?.count ?? 0
}
...
.chartXVisibleDomain(length: 3600 * 24 * days)
...
.chartScrollPosition(x: $scrollPosition)
...

But I found that it does not work as expected. 😢

Answered by in 792445022

Both southr's original post and jlilest's suggestion are correct.

Swift Charts currently only has a continuous time scale / axis, therefore, any unit of time that may vary will vary.

Scrolling along an underlying time scale (Plottable is Date) has the same limitation; time is modeled as continuous.

The current workaround is the choice of the desired temporal resolution, eg. monthly, using a categorical scale/axis (where the Plottable value is a String).

Scrolling is supported for categorical scales too.

What about creating a view that shows data for a month. Create an outer data model with a list of months to show that drives a scrollable list.

Accepted Answer

Both southr's original post and jlilest's suggestion are correct.

Swift Charts currently only has a continuous time scale / axis, therefore, any unit of time that may vary will vary.

Scrolling along an underlying time scale (Plottable is Date) has the same limitation; time is modeled as continuous.

The current workaround is the choice of the desired temporal resolution, eg. monthly, using a categorical scale/axis (where the Plottable value is a String).

Scrolling is supported for categorical scales too.

How can Charts display sales data for a full month and support monthly paging?
 
 
Q