我用小卡片视图的网格替换了您示例的图像。
我们将尝试更改被拖动手势“交叉”的卡片的颜色。
我们可以使用PreferenceKey 来获取所有CardViews 边界...
struct CardPreferenceData: Equatable {
let index: Int
let bounds: CGRect
}
struct CardPreferenceKey: PreferenceKey {
typealias Value = [CardPreferenceData]
static var defaultValue: [CardPreferenceData] = []
static func reduce(value: inout [CardPreferenceData], nextValue: () -> [CardPreferenceData]) {
value.append(contentsOf: nextValue())
}
}
这里:
struct CardView: View {
let index: Int
var body: some View {
Text(index.description)
.padding(10)
.frame(width: 60)
.overlay(RoundedRectangle(cornerRadius: 10).stroke())
.background(
GeometryReader { geometry in
Rectangle()
.fill(Color.clear)
.preference(key: CardPreferenceKey.self,
value: [CardPreferenceData(index: self.index, bounds: geometry.frame(in: .named("GameSpace")))])
}
)
}
}
现在我们可以在 ContentView 中收集这些卡片的所有首选项(边界和索引)并将它们存储在一个数组中:
.onPreferenceChange(CardPreferenceKey.self){ value in
cardsData = value
}
我们现在可以将这些 CardView 的位置(bounds)与拖动手势的位置进行比较。
struct ContentView: View {
let columns = Array(repeating: GridItem(.fixed(60), spacing: 40), count: 3)
@State private var selectedCardsIndices: [Int] = []
@State private var cardsData: [CardPreferenceData] = []
var body: some View {
LazyVGrid(columns: columns, content: {
ForEach((1...12), id: \.self) { index in
CardView(index: index)
.foregroundColor(selectedCardsIndices.contains(index) ? .red : .blue)
}
})
.onPreferenceChange(CardPreferenceKey.self){ value in
cardsData = value
}
.gesture(
DragGesture()
.onChanged {drag in
if let data = cardsData.first(where: {$0.bounds.contains(drag.location)}) {
selectedCardsIndices.append(data.index)
}
}
)
.coordinateSpace(name: "GameSpace")
}
}
编辑:视频开头的小“滞后”不会出现在画布上。只在模拟器上。我没有在真机上测试过。