Finally with Xcode 15 and iOS 17 you can make your SwiftUI Charts scrollable.
Apple introduced some new APIs that make this process easy and customisable.
func chartScrollableAxes(_ axes: Axis.Set)
Here you can choose whether to scroll your chart
func chartXVisibleDomain(length: P)
func chartYVisibleDomain(length: P)
Use this method to control how much of the chart is visible.
For example, in the bar chart, the length is the number of bars you want to be visible, the exceeding bars will be hidden and the user will have to scroll to see them.
func chartScrollPosition(x: Binding<some Plottable>)
func chartScrollPosition(y: Binding<some Plottable>)
This methods gives you the current scroll position.
To use it, declare a
@State variable and pass it to the method.
@State var xScrollPosition: Double = 0
Initial scroll position
func chartScrollPosition(initialX: some Plottable)
func chartScrollPosition(initialY: some Plottable)
Use this method to provide the initial position of the chart.
This example will set the initial scroll position to the 4th bar.
let data = [Entry(x: 0, y: 43),
Entry(x: 1, y: 53),
Entry(x: 2, y: 25),
Entry(x: 3, y: 43),
Entry(x: 4, y: 73),
Entry(x: 5, y: 24),
Entry(x: 6, y: 82),
Entry(x: 7, y: 37),
Entry(x: 8, y: 66),
Entry(x: 9, y: 33)]
Here, in the
chartScrollPosition(initialX:) method we pass the
x value we want the chart to start from.
func chartScrollTargetBehavior(_ behavior: some ChartScrollTargetBehavior)
This method controls to which bar the chart will snap once the user stops scrolling.
An basic implementation of this method is this:
Here the chart will snap every 2 bars.
This is a great addition to the great SwiftUI Charts library, since there are many scenarios where charts can have a lot of data.
But unfortunately these features are available only in iOS 17 for now.
I hope Apple will in future back deploy these methods also for iOS 16.
These SwiftUI APIs are still in Beta and may change in future.
What are you thoughts about this? Tweet me @franceleonidev and share your opinion.