swift - 如何通过 SwiftUI Tap Gesture 使用键修饰符(选项/命令/控制)

标签 swift macos swiftui gesture macbookpro-touch-bar

我正在尝试在我的 swiftUI View 中使用带有点击手势的键修饰符。我希望在注册点击手势时执行一个操作,并在按住命令+点击手势时执行一个单独的操作。

我测试了这里使用的代码来回答这个确切的问题:Check state of Option-Key in SwiftUI (macOS)

我已经在普通的 swiftUI View 中测试了这段代码,它似乎工作正常。

但是,我想使用它的 View 显示在触摸栏上。使用触摸栏进行测试时,它会注册一个正常的点击手势,但不会注册一个带有修饰符的点击手势。有什么我在这里想念的吗?谢谢您的帮助。我的触摸栏 View 代码是这样的:

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")
            }

最佳答案

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

        .onTapGesture {
            print("Tap with option: \(NSEvent.modifierFlags.contains(.option))")
        }

关于swift - 如何通过 SwiftUI Tap Gesture 使用键修饰符(选项/命令/控制),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66019823/

相关文章:

ios - 解析 API - Facebook 登录在 iPhone 设备上不起作用

ios - 界面 View : addConstraint fails with EXC_BAD_INSTRUCTION unless no-op constraints() is called first

macos - 如何确定 NSURL 是否具有安全范围信息?

swift - 支持不同 SwiftUI View 类型的 UIHostingController 数组

ios - SwiftUI:VStack 中的 VStack,标签被截断

ios - 如何使用字体修改器? SwiftUI 中的大写和字体大小

ios - 解析 "cannot sign up without username"

arrays - 快速删除数组范围内的对象

xcode - 验证 GateKeeper (Sierra) 的 OSX 应用程序签名时出现问题 ["the code is valid but does not seem to be an app"]

macos - cocoa osx 以编程方式添加 nstextfields