问题描述
我试图在我的 swiftUI 视图中使用带有点击手势的按键修饰符。我想在注册点击手势时执行一个操作,并在按住命令 + 点击手势时执行一个单独的操作。
我测试了此处使用的代码来回答这个确切的问题:Check state of Option-Key in SwiftUI (macOS)
我已经在普通的 swiftUI 视图中测试了这段代码,它似乎工作正常。
但是,我想与它一起使用的视图显示在触摸栏上。使用触摸条进行测试时,它会注册一个普通的点击手势,但不会注册带有修饰符的点击手势。有什么我在这里想念的吗?谢谢您的帮助。我的触摸栏视图代码是这样的:
struct SoundChartView: View {
@Observedobject var modal = ChartModal()
var barWidth: CGFloat = 4.0
let barSpace: CGFloat = 1.0
var body: some View {
GeometryReader { geo in
ZStack {
colorView().mask(
ZStack {
// right channel
BarChart(vector: modal.vectorRight,barWidth: barWidth + 1)
.stroke(Color.white,linewidth: barWidth)
// left channel
BarChart(vector: modal.vector,linewidth: barWidth)
}
)
.animation(
Animation.eaSEOut(duration: 0.1)
)
.gesture(TapGesture().modifiers(.option).onEnded {
print("Do anyting on OPTION+CLICK")
})
.onTapGesture(count: 2,perform: {
print("double tap")
})
.onTapGesture() {
print("tapped")
}
.onLongPressGesture() {
print("long press")
}
解决方法
您可以使用 NSEvent.modifierFlags 作为后备:
.onTapGesture {
print("Tap with option: \(NSEvent.modifierFlags.contains(.option))")
}