我目前正在开发一个
SwiftUI
项目,我需要在包含多个按钮的视图上实现真正的多点触控支持。现有的实现支持拖动这些按钮来更新 activeButtonIndex
状态,突出显示当前拖动的按钮。但目前仅支持单点触控交互。我想增强它以支持多点触控,如果使用多个手指,可以同时激活多个按钮。
我想保留所有当前功能。具体来说,我正在寻找一种仅限
SwiftUI
的解决方案,而不求助于 UIKit
互操作。
我尝试参考Apple的开发者文档文章编写SwiftUI手势无济于事。
这是我当前代码的简化版本:
import SwiftUI
struct ContentView: View {
@State private var activeButtonIndex: Int? = nil
@State private var buttonFrames: [CGRect] = Array(repeating: .zero, count: 11)
private let buttonCount = 11
var body: some View {
VStack {
activeButtonView
buttonsView
}
.gesture(dragGesture)
}
private var activeButtonView: some View {
Text("Active Button \(activeButtonIndex.map { "\n\($0 + 1)" } ?? "\nNone")")
.multilineTextAlignment(.center)
.padding()
}
private var buttonsView: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(0 ..< buttonCount, id: \.self) { index in
Button(action: {}) {
EmptyView()
}
.frame(width: 70, height: 210)
.background(backgroundForButton(at: index))
.overlay(GeometryReader { geometry in
Color.clear.onAppear {
buttonFrames[index] = geometry.frame(in: .global)
}
})
}
}
}
}
private func backgroundForButton(at index: Int) -> Color {
activeButtonIndex == index ? .green : .blue
}
private var dragGesture: some Gesture {
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onChanged { value in
updateActiveButton(with: value.location)
}
.onEnded { _ in
activeButtonIndex = nil
}
}
private func updateActiveButton(with location: CGPoint) {
for (index, frame) in buttonFrames.enumerated() {
if frame.contains(location) {
activeButtonIndex = index
return
}
}
activeButtonIndex = nil
}
}
有没有人实现了类似的东西,或者可以指导我如何在这种情况下添加多点触控支持?任何建议或例子将不胜感激。
你尝试过
simultaneousGesture
吗?VStack(spacing: 100) {
Text("First button")
.gesture(
DragGesture()
.onEnded { _ in
print("First button tapped")
}
)
Text("Second button")
.simultaneousGesture(
DragGesture()
.onEnded { _ in
print("Second button tapped")
}
)
}