onHover broken when acceptsMouseMovedEvents true

Create a empty AppKit project and replace the ViewController.swift

import Cocoa
import SwiftUI

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let hostingView = NSHostingView(rootView: ButtonView())
        view.addSubview(hostingView)
        hostingView.frame = NSRect(x: 50, y: 100, width: 100, height: 40)
    }

    override func viewDidAppear() {
        super.viewDidAppear()

        view.window?.acceptsMouseMovedEvents = true
    }
}

struct ButtonView: View {
    @State var isPresented = false

    var body: some View {
        Button("Click me") {
            isPresented = true
        }
        .popover(isPresented: $isPresented, arrowEdge: .trailing) {
            Button("Hello world", action: {

            })
            .padding()
            .onHover { hover in
                print(hover)
            }
        }
    }
}

If set the window.acceptsMouseMovedEvents to true, the onHover of button in popover is broken.

How to resolve it?

Setting the acceptsMouseMovedEvents property on NSWindow has been strongly discouraged for a long, long time. It potentially triggers a flood of events, most of which end up being ignored.

The better AppKit alternative is to use NSTrackingArea. It also uses mouseMoved event functions, but limits the event stream to just the relevant area so it performs more reliably.

onHover broken when acceptsMouseMovedEvents true
 
 
Q