How to get the on-screen location of an NSStatusItem

前端 未结 7 705
暖寄归人
暖寄归人 2020-12-05 01:27

I have a question about the NSStatusItem for cocoa in mac osx. If you look at the mac app called snippets (see the movie at http://snippetsapp.com/). you will s

7条回答
  •  情话喂你
    2020-12-05 01:49

    Given an NSMenuItem and an NSWindow, you can get the point that centers your window right below the menu item like this:

    fileprivate var centerBelowMenuItem: CGPoint {
        guard let window = window, let barButton = statusItem.button else { return .zero }
        let rectInWindow = barButton.convert(barButton.bounds, to: nil)
        let screenRect = barButton.window?.convertToScreen(rectInWindow) ?? .zero
        // We now have the menu item rect on the screen.
        // Let's do some basic math to center our window to this point.
        let centerX = screenRect.origin.x-(window.frame.size.width-barButton.bounds.width)/2
        return CGPoint(x: centerX, y: screenRect.origin.y)
    }
    

    No need for undocumented API's.

提交回复
热议问题