Swift:如何使用 SwiftUI 应用 "acceptsFirstMouse" 构建应用程序?

Swift: how to apply "acceptsFirstMouse" for app build with SwiftUI?

假设我有一个适用于 MacOS (Catalina) 的应用程序。

此应用未隐藏。但是另一个应用程序被激活(最前面/最上面)

我想点击 button/any 其他视图 (我使用的是 swiftUI,所以一切都是视图) 以防点击我的应用程序。

我该怎么做?


UPD:如何应用 "acceptsFirstMouse" 使用 SwiftUI 构建应用程序?

好吧,目前 SwiftUI 中还没有这样的工具 API,但是......它不是在沙漠中独立存在的,Apple 也没有说它是 Cocoa 的替代品,此外,他们向我们展示了如何整合它们并充分利用两者...

所以,这是可能的方法...

import SwiftUI
import Cocoa

// Just mouse accepter
class MyViewView : NSView {
    override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
        return true
    }
}

// Representable wrapper (bridge to SwiftUI)
struct AcceptingFirstMouse : NSViewRepresentable {
    func makeNSView(context: NSViewRepresentableContext<AcceptingFirstMouse>) -> MyViewView {
        return MyViewView()
    }

    func updateNSView(_ nsView: MyViewView, context: NSViewRepresentableContext<AcceptingFirstMouse>) {
        nsView.setNeedsDisplay(nsView.bounds)
    }

    typealias NSViewType = MyViewView
}

// Usage (somewhere in your SwiftUI view stack)
...
      Text("Click me")
        .padding(20)
        .background(Color.yellow)
        .overlay(AcceptingFirstMouse()) // must be on top (no confuse, it is transparent)
        .onTapGesture {
            print("Label tapped")
        }
...