如何在 SwiftUI iOS 中初始化图表后动态更新图表 x 轴

问题描述 投票:0回答:1
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 图表中可能吗?

ios swift swiftui charts swiftui-charts
1个回答
1
投票

您可以通过视图模型中的@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
        }
    }
}}
© www.soinside.com 2019 - 2024. All rights reserved.