import SwiftUI
import Charts
struct ContentView: View {
@State private var numbers = (0..<100)
.map { _ in Double.random(in: 0...100) }
@State private var scrollPosition = 0
@State var xAxisRange: ClosedRange<Int> = 0 ... 50
var body: some View {
Chart(Array(zip(numbers.indices, numbers)), id: \.1) { index, number in
LineMark(
x: .value("Index", index),
y: .value("Number", number)
)
}
.chartScrollableAxes(.horizontal)
.chartXScale(domain: xAxisRange)
.chartScrollTargetBehavior(
.valueAligned(
unit: 5,
majorAlignment: .page
)
)
.chartScrollPosition(x: $scrollPosition)
.onChange(of: scrollPosition) {
print(scrollPosition)
if scrollPosition > 30 {
xAxisRange = 0 ... 100
}
}
}
}
这是示例代码,我正在尝试加载动态数据,例如图表中的分页,但是当我更新 x 轴滚动时,它会受到干扰,并且它将远离当前数据。
无论我尝试什么,这在 SwiftUI 图表中可能吗?
您可以通过视图模型中的@StateObject和@Published来完成:
import SwiftUI
import Charts
class ViewModel: ObservableObject {
@Published var xAxisRange1: ClosedRange<Int> = 0 ... 50
}
struct ContentView: View {
@State private var numbers = (0..<100).map { _ in Double.random(in: 0...100) }
@State private var scrollPosition = 0
@StateObject private var vm = ViewModel()
var body: some View {
Chart(Array(zip(numbers.indices, numbers)), id: \.1) { index, number in
LineMark(
x: .value("Index", index),
y: .value("Number", number)
)
}
.chartScrollableAxes(.horizontal)
.chartXScale(domain: vm.xAxisRange1)
.chartScrollTargetBehavior(
.valueAligned(
unit: 5,
majorAlignment: .page
)
)
.chartScrollPosition(x: $scrollPosition)
.onChange(of: scrollPosition) {
print(scrollPosition)
if scrollPosition > 30 {
vm.xAxisRange1 = 0 ... 100
}
}
}}