在 SwiftUI 中更新路径

Updating Path in SwiftUI

我有一个带有图表的 SwiftUI 视图,它是使用 entries 数组中的路径和数据制作的。

代码:

struct TodayChartView: View {
    var body: some View {
            GeometryReader { reader in
                    Path { p in
                            for i in 1..<entries.count {
                                p.move(to: CGPoint(x: entries[i-1].x, entries[i-1].y: y))
                                p.addLine(to: CGPoint(entries[i].x: x, entries[i].y: y))
                            }
                        }
                    }.stroke(Color.blue, style: StrokeStyle(lineWidth: 3, lineCap: .round, lineJoin: .round))
                }
}

当用户在另一个视图中按下按钮时,一个新条目将添加到 entries,我想将其显示在我的路径上。所以,基本上,我需要以某种方式触发重绘它。有什么办法可以实现吗?

试试这个

    Path { p in
            for i in 1..<entries.count {
                p.move(to: CGPoint(x: entries[i-1].x, entries[i-1].y: y))
                p.addLine(to: CGPoint(entries[i].x: x, entries[i].y: y))
            }
        }
    }.stroke(Color.blue, style: StrokeStyle(lineWidth: 3, lineCap: .round, lineJoin: .round))
    .id(entries)     // << here !!

entries 作为参数传递给 TodayChartView。将 entries 作为 ContentView 中的 @State var,只要 entries 发生变化,TodayChartView 就会重新绘制。

这是一个完整的示例(在 Xcode 11.7 中测试):

struct TodayChartView: View {
    let entries: [CGPoint]
    
    var body: some View {
        // GeometryReader { reader in
            Path { p in
                for i in 1..<self.entries.count {
                    p.move(to: CGPoint(x: self.entries[i-1].x, y: self.entries[i-1].y))
                    p.addLine(to: CGPoint(x: self.entries[i].x, y: self.entries[i].y))
                }
            }
            .stroke(Color.blue, style: StrokeStyle(lineWidth: 3, lineCap: .round, lineJoin: .round))
        // }
    }
}

struct ContentView: View {
    @State private var entries: [CGPoint] = [CGPoint(x: 150, y: 150)]
    
    var body: some View {
        VStack(spacing: 20) {
            Button("Add Point") {
                let x = CGFloat.random(in: 0...300)
                let y = CGFloat.random(in: 0...300)
                self.entries.append(CGPoint(x: x, y: y))
            }
            TodayChartView(entries: self.entries)
                .frame(width: 300, height: 300)
        }
    }
}

注意:您的TodayChartView当前未使用GeometryReader,所以我已将其注释掉。