I'm using swift Charts with a fairly basic setup (data from Core Data fetchrequest which works fine):
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)
.chartXScale(domain: startDate...endDate)
After adding .chartScrollableAxes and .chartScrollPosition it works fine until I also start adjusting .chartXVisibleDomain(length: ). I have that linked to an @State from a picker adjusting the seconds to display.
@State private var xChartVisible : Int = 3600 * 24 * 90
@State private var xScrollPosition : TimeInterval = TimeInterval()
@State private var xInitialPosition : Date = Date()
xScrollPosition is a TimeInterval as I'm also using this to get the dates from the chart to show above the chart to show the date range.
Everything still works great except for when I'm selecting different date periods from the Picker (I have month, quarter, half year and year). the length updates correctly but in most instances the chart then completely changes it's date area. How do I get the date location in the chart to stay in roughly the same position when the date range changes?
I've noticed $xScrollPosition number remains exactly the same even when the range changes which may be the cause of it jumping position, but not sure what to do about this.
.onAppear {
xInitialPosition = weightPeriodFunc.initialScrollDate
xScrollPosition = weightPeriodFunc.initialScrollDate.timeIntervalSinceReferenceDate
xChartVisible = weightPeriodFunc.length
}
.onChange(of: weightPeriod) { newValue in
withAnimation(.linear(duration: 1)) {
xChartVisible = weightPeriodFunc.length
xScrollPosition = newPeriodStartDate.timeIntervalSinceReferenceDate
}
}
Trying to do something with xScrollPosition on change, but not sure what, if anything as it seems it's meant to update by itself. Any help would be greatly appreciated, thank you.