3

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Andrew_STOP_RU_WAR_IN_UA
  • 9,318
  • 5
  • 65
  • 101
  • You can't, simply – Orkhan Alikhanov Dec 01 '19 at 21:34
  • @matt in case of this is impossible, "ubar" cannot exist, but it is exist. As any other "external" and not build-in dock alternative. And such apps HAVE SUCH BEHAVIOR. So.... You're not right. It's possible, but you just don't know how. – Andrew_STOP_RU_WAR_IN_UA Dec 01 '19 at 21:37
  • Chill out Andrew, matt is an expert and writing best books on iOS programming and Swift Language. Your question is ambiguous, you should've tagged it with macOS specifically. – Orkhan Alikhanov Dec 01 '19 at 21:46
  • So now it's just a duplicate of https://stackoverflow.com/questions/128015/make-osx-application-respond-to-first-mouse-click-when-not-focused and many others. – matt Dec 01 '19 at 21:47
  • 1
    It is not duplicate because of `SwiftUI` tag. There is no such information for swiftUI on SO and any any other resource. I have checked. – Andrew_STOP_RU_WAR_IN_UA Dec 01 '19 at 22:26
  • You are the one who has elected to throw away the yummy goodness of Cocoa and use SwiftUI instead. `acceptsFirstMouse` is Cocoa. – matt Dec 02 '19 at 01:44

1 Answers1

4

Well, for now there is no such instrument in SwiftUI API, but... it is not standalone in a desert, and Apple did not say that it is a replacement for Cocoa, moreover they show us how to integrate them and use best of both...

So, here is possible approach...

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")
        }
...
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690