NSPopover 并使用 NSStatusItem 添加间距

NSPopover and adding spacing with NSStatusItem

我正在开发一个使用 NSPopover 的菜单栏应用程序。我正在使用以下代码来呈现弹出窗口。

[self.mainPopover showRelativeToRect:[testView bounds] ofView:testView preferredEdge:NSMinYEdge];

问题是它离状态栏太近了,如下所示。

即使我更改了矩形,它也没有任何效果,而且确实如此,正如文档所述

The rectangle within positioningView relative to which the popover should be positioned. Normally set to the bounds of positioningView. May be an empty rectangle, which will default to the bounds of positioningView.

以下是 dropbox 应用程序的屏幕截图,我只是想知道如何在我的应用程序中添加一些间距,例如 dropbox。

您可以插入测试视图边界以在 de view 和 popover 之间添加一些边距:

NSPopover *mainPopover = [self mainPopover];
NSRect bounds = CGRectInset([testView bounds], -50.0, -50.0);
[mainPopover showRelativeToRect:bounds ofView:testView preferredEdge:NSMinYEdge];

为了实现这一点,我添加了一个填充视图并将集合 NSStatusItem 视图附加到该容器视图。所用解决方案的代码如下,供任何希望实施它的人使用。

_paddingView = [NSView new];
[_containerView addSubview:_paddingView];
[_containerView addSubview:_dragView];

[_dragView      setTranslatesAutoresizingMaskIntoConstraints:NO];
[_paddingView   setTranslatesAutoresizingMaskIntoConstraints:NO];
[_containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_dragView(22)][_paddingView(5)]|"                                                                                                                 options:0
                                                                       metrics:nil views:views]];
[_containerView addConstraint:[NSLayoutConstraint constraintWithItem:_dragView
                                                           attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual
                                                              toItem:_paddingView attribute:NSLayoutAttributeLeft
                                                          multiplier:1. constant:0]];
[_containerView addConstraint:[NSLayoutConstraint constraintWithItem:_dragView
                                                           attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual
                                                              toItem:_paddingView attribute:NSLayoutAttributeRight
                                                          multiplier:1. constant:0]];

self.mainPopover = [[NSPopover alloc] init];
self.mainPopover.delegate = self;
self.mainPopover.backgroundColor = [NSColor greenColor];
[self.mainPopover setAnimates:NO];
[self.mainPopover setBehavior:NSPopoverBehaviorTransient];
[self.mainPopover setContentViewController:viewController];

[_containerView layoutSubtreeIfNeeded];

[_statusItem setView:_containerView];