如何在距系统栏一定距离的地方打开NSPopover? [英] How to open a NSPopover at a distance from the system bar?
问题描述
我正在状态栏中通过图标打开NSPopover
.
I'm opening a NSPopover
with the action of an icon in the status bar.
myPopover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
除了弹出窗口和系统栏的距离为零之外,这可以很好地工作:
This works fine with the exception that the distance from the popover and the system bar is zero:
我想要获得与Dropbox应用相同的结果,该应用将弹出窗口呈现在距离系统栏一小段距离的地方:
I'd like to achieve the same result as the Dropbox app which renders the popover at a small distance from the system bar:
我尝试使用button.bounds.offsetBy(dx: 0.0, dy: 20.0)
,它不影响弹出窗口的位置,而button.bounds.offsetBy(dx: 0.0, dy: -20.0)
则将弹出窗口置于系统栏上方:
I've tried using button.bounds.offsetBy(dx: 0.0, dy: 20.0)
which doesn't affect the position of the popover and button.bounds.offsetBy(dx: 0.0, dy: -20.0)
which puts the popover above the system bar:
那么如何将NSPopover
放置在距系统栏一定距离的地方?
So how can I position the NSPopover
at some distance from the system bar?
推荐答案
首先,button.bounds.offsetBy(dx: 0.0, dy: -20.0)
无效的原因是,这些坐标落在状态栏项目本身即状态栏项目的窗口"之外.所以它外面的任何东西都被裁剪掉了.
First, the reason why button.bounds.offsetBy(dx: 0.0, dy: -20.0)
didn't work is because those coordinate fell outside the "window" of the status bar item which is the status bar itself. So anything outside of it was cropped.
我通过在各处收集信息解决了这个问题:
I solved this problem by collecting information here and there:
- 创建一个不可见的窗口.
- 在状态栏项目的屏幕中找到坐标,并将不可见的窗口置于其下方.
- 相对于不可见窗口而不是状态栏项目显示
NSPopover
.
红色的东西是不可见的窗口(出于演示目的).
The red thing is the invisible window (for demonstration purposes).
// Create a window
let invisibleWindow = NSWindow(contentRect: NSMakeRect(0, 0, 20, 5), styleMask: .borderless, backing: .buffered, defer: false)
invisibleWindow.backgroundColor = .red
invisibleWindow.alphaValue = 0
if let button = statusBarItem.button {
// find the coordinates of the statusBarItem in screen space
let buttonRect:NSRect = button.convert(button.bounds, to: nil)
let screenRect:NSRect = button.window!.convertToScreen(buttonRect)
// calculate the bottom center position (10 is the half of the window width)
let posX = screenRect.origin.x + (screenRect.width / 2) - 10
let posY = screenRect.origin.y
// position and show the window
invisibleWindow.setFrameOrigin(NSPoint(x: posX, y: posY))
invisibleWindow.makeKeyAndOrderFront(self)
// position and show the NSPopover
mainPopover.show(relativeTo: invisibleWindow.contentView!.frame, of: invisibleWindow.contentView!, preferredEdge: NSRectEdge.minY)
NSApp.activate(ignoringOtherApps: true)
}
我正在尝试使用show(relativeTo: invisibleWindow.frame ...)
,并且没有显示弹出窗口,因为NSWindow
不是NSView
.为了显示弹出窗口,必须通过视图.
I was trying to use show(relativeTo: invisibleWindow.frame ...)
and the popup wasn't showing up because NSWindow
is not an NSView
. For the popup to be displayed a view has to be passed.
这篇关于如何在距系统栏一定距离的地方打开NSPopover?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!