NSView as child of NSWindow.contentView lose interaction

38 Views Asked by At

I have an issue where my NSView does not respond to mouse events and interactions.
If the NSView is the NSWindow.contentView, it works.
If the NSView is added as a child view of the default NSWindow.contentView, we can't interact with it (mouse events don't work).
I need the second option as my NSView isn't shorter that the NSWindow and I need to center it in it (therefore I need to add constraints on a intermediate view: The default contentView in this case).

Here is a reproductible example:

import Cocoa
import SwiftUI
import AppKit

struct MyView: View {
    var body: some View {
        Rectangle()
            .frame(width: 300, height: 300)
            .onTapGesture {
                print("Clicked me baby, one more time!")
            }
        .background(.red)
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let window = NSWindow()
        let view = NSHostingView(rootView: MyView())
        view.setFrameOrigin(NSPoint(x: 50,y: 50))
        let wrapperView = NSView()
        
        wrapperView.addSubview(view)
        window.contentView?.addSubview(wrapperView) // <-- This doesn't work
        //window.contentView = wrapperView          // <-- This work
        window.makeKeyAndOrderFront(nil)
        window.setIsVisible(true)
    }
}

Any help is welcome! Thanks

0

There are 0 best solutions below