我正在使用几何读取器跟踪矩形网格中所有矩形的位置,以便稍后与它们进行交互。现在我想添加放大和滚动到网格的选项。然而,当放大预览时,几何图形读取器似乎会变得混乱,并且当缩放发生变化时,位置不会更新。有办法解决这个问题吗?
import SwiftUI
struct GridTestView: View {
@State private var currentScale: CGFloat = 1.0
@State private var baseScale: CGFloat = 1.0
var tileList = [[1,1],[2,1],[3,1],[2,2]]
@State var tileFrames = [CGRect](repeating: .zero, count: 4)
var body: some View {
grid
}
var grid: some View {
Grid(horizontalSpacing: 0, verticalSpacing: 0) {
ForEach((1...2).reversed(), id: \.self) { j in
GridRow {
ForEach(1...3, id: \.self) { i in
if tileList.contains(where: {$0 == [i,j]}) {
let currentTileIndex = tileList.firstIndex(where: {$0 == [i,j]})!
Rectangle()
.fill(.gray)
.stroke(.primary, lineWidth: 1)
.aspectRatio(1, contentMode: .fit)
.overlay(
GeometryReader { geo in
Color.clear
.onAppear {
self.tileFrames[currentTileIndex] = geo.frame(in: .global)
}
}
)
}
else {
Color.clear
.aspectRatio(1.0, contentMode: .fit)
}
}
}
}
}
.scaleEffect(currentScale)
.gesture(
MagnificationGesture()
.onChanged { value in
currentScale = baseScale * value
}
.onEnded { value in
baseScale = currentScale
}
)
}
}
#Preview {
GridTestView()
}
也许作为一个额外的问题:如果网格也是 ScrollView 的一部分,我该如何处理它?
一个简单的 ''' .onChange(of: self.currentScale) { self.tileFrames[currentTileIndex] = geo.frame(in: .global) } ''' 解决了这个问题。但是,我仍然很好奇在使用 ScrollView ontop 时如何处理同样的问题!