Make your Chart Scrollable with SwiftUI Charts (iOS 17)
Discover the new SwiftUI Charts APIs that enables you to create scrollable chart easily. Available for Xcode 15 and iOS 17.
• 2 min read
Availability
Xcode 15
iOS 17
macOS 14
tvOS 17
watchOS 10
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.
APIs
Scroll direction
func chartScrollableAxes(_ axes: Axis.Set)
Here you can choose whether to scroll your chart vertically
or horizontally
.
Visible domain
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.
Scroll position
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
Chart {
// ...
}
.chartScrollableAxes(.horizontal)
.chartScrollPosition(x: $xScrollPosition)
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)]
Chart(entry) {
// ...
}
.chartScrollableAxes(.horizontal)
.chartScrollPosition(initialX: 4)
Here, in the chartScrollPosition(initialX:)
method we pass the x
value we want the chart to start from.
Scroll behavior
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:
Chart {
// ...
}
.chartScrollableAxes(.horizontal)
.chartScrollTargetBehavior(.valueAligned(unit: 2))
Here the chart will snap every 2 bars.
Conclusion
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.
If you have any question about this article, feel free to email me or tweet me @franceleonidev and share your opinion.
Thank you for reading and see you in the next article!
Share this article