swiftmacosswiftuimacos-catalina

How to apply "acceptsFirstMouse" for app build with SwiftUI?


Let's imagine that I have an app for macOS (Catalina).

This app is not hidden. But another app is activated (front of all/ top most)

I want to catch click on the button/any other view (I'm using swiftUI, so everithing is a view) in case of click on my app.

How can I do this?


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


Solution

  • You can create custom window from AppDelegate and use custom NSHostingView that accepts first click

    @available(macOS 10.15, *)
    public class FirstClickNSHostingView<Content>: NSHostingView<Content> where Content : View {
        public override var acceptsFirstResponder: Bool {
            true
        }
        
        public override func acceptsFirstMouse(for event: NSEvent?) -> Bool {
            true
        }
    }