我有以下代码创建了一个网格,并使用数组中的字符填充它。我已经添加了手势代码,但是它可以在整个网格上拖动,而不是在单个单元格上拖动。
import SwiftUI
struct GridStack<Content: View>: View {
let rows: Int
let columns: Int
let content: (Int, Int) -> Content
@State private var currentPosition: CGSize = .zero
@State private var oldPosition: CGSize = .zero
@State private var newPosition: CGSize = .zero
var body: some View {
VStack {
ForEach(0 ..< rows, id: \.self) { row in
HStack(spacing: 0) {
ForEach(0 ..< self.columns, id: \.self) { column in
self.content(row, column).font(.custom("Rockwell",size:24)).frame(width: 30, height: 30).padding()
}.border(Color.gray)
.offset(x: self.currentPosition.width, y: self.currentPosition.height)
.gesture(DragGesture()
.onChanged { value in
self.currentPosition = CGSize(width: value.translation.width + self.newPosition.width, height: value.translation.height + self.newPosition.height)
} // 4.
.onEnded { value in
self.currentPosition = self.oldPosition
self.newPosition = self.oldPosition
}
)
}
}
}
}
init(rows: Int, columns: Int, @ViewBuilder content: @escaping (Int, Int) -> Content) {
self.rows = rows
self.columns = columns
self.content = content
}
}
如何在每个单元格上启用拖动?