Hi, I'm making use of iOS17 Charts and getting data from Core Data.
Chart {
ForEach(weightContext, id: \.timestamp) { series in
LineMark(
x: .value("Day", series.timestamp!, unit: .day),
y: .value("Measurement", WeightFunctions.weightConversions(weightValue: series.value, metric: selectedWeight))
)
PointMark(
x: .value("Day", series.timestamp!, unit: .day),
y: .value("Measurement", WeightFunctions.weightConversions(weightValue: series.value, metric: selectedWeight))
)
}
}
.chartYScale(domain: lowestValue...highestValue)
.chartScrollableAxes(.horizontal)
.chartXVisibleDomain(length: xChartVisible)
.chartScrollPosition(x: $xScrollPosition)
.chartScrollPosition(initialX: xInitialPosition)
// .chartXVisibleDomain(length: xChartVisible)
.chartXScale(domain: startDate...endDate)
I've linked the .chartXVisibleDomain(length: xChartVisible) to a Picker which changes the length to show month, quarter, half year, year:
length = 3600 * 24 * 30, length = 3600 * 24 * 90 etc.
Each time the xChartVisible changes the chart sometimes stays in the right area if I'm at the end of the x axis, but otherwise moves out of the view. I've noticed the $xScrollPosition number stays exactly the same, even though the visibility has changed but not sure what to do about that.
.onAppear {
xInitialPosition = weightPeriodFunc.initialScrollDate
xScrollPosition = weightPeriodFunc.initialScrollDate.timeIntervalSinceReferenceDate
xChartVisible = weightPeriodFunc.length
}
.onChange(of: weightPeriod) { newValue in
xChartVisible = weightPeriodFunc.length
xScrollPosition = newPeriodStartDate.timeIntervalSinceReferenceDate
}
I've set the xScrollPosition as a TimerInterval as I'm also getting the dates from it's location to provide date information above the chart.
@State private var xChartVisible : Int = 3600 * 24 * 90
@State private var xScrollPosition : TimeInterval = TimeInterval()
@State private var xInitialPosition : Date = Date()
@State private var newPeriodStartDate : Date = Date()