如何通过 SwiftUI 点击手势使用按键修饰符(选项/命令/控制)

Jak*_*e F 5 macos gesture swift macbookpro-touch-bar swiftui

我正在尝试在 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, barWidth: barWidth + 1)
                        .stroke(Color.white, 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")
            }
Run Code Online (Sandbox Code Playgroud)

小智 13

您可以使用 NSEvent.modifierFlags 作为后备:

        .onTapGesture {
            print("Tap with option: \(NSEvent.modifierFlags.contains(.option))")
        }
Run Code Online (Sandbox Code Playgroud)