SwiftUI/iOS 17 how to limit size of scrollable Chart for Dates ? `chartXVisibleDomain(length:)` not working

28 Views Asked by At

I want to display a SwiftUI scrollable Chart with Dates on the X axis, but I want to limit the number of dates visible at once on the screen (only display 7 days for instance) Chart not limited on X axis

Since iOS 17 we have https://developer.apple.com/documentation/swiftui/view/chartscrollableaxes(\_:) and https://developer.apple.com/documentation/swiftui/view/chartxvisibledomain(length:)

chartXVisibleDomain(length:) is supposed to limit the number of items visible, and it does work for when my X axis items are just Ints, but when they are Dates, I just get a blank screen with no log/error

This works correctly:

struct GraphView: View {
    static let items = 1...100
    var body: some View {
        Chart {
            ForEach(Self.items, id: \.self) { i in
                PointMark(
                    x: .value("x", i),
                    y: .value("y", i)
                )
            }
        }
        .chartScrollableAxes(.horizontal)
        .chartXVisibleDomain(length: 10)
    }
}

But this gives a blank screen:

struct GraphView: View {
    static let items = Array(
        stride(
            from: Date.now.addingTimeInterval(-30 * 24 * 60 * 60),
            to: Date.now,
            by: 100
        )
    )
    var body: some View {
        Chart {
            ForEach(Self.items.indices, id: \.self) { index in
                LineMark(
                    x: .value("x", Self.items[index], unit: .day),
                    y: .value("y", index)
                )
            }
        }
        .chartScrollableAxes(.horizontal)
        .chartXVisibleDomain(length: 10)
    }
}

You can comment .chartScrollableAxes(.horizontal) and .chartXVisibleDomain(length: 10) and you'll get a result, but the number of visible items on the X axis will not be limited

0

There are 0 best solutions below