objective-cmacosnsstatusitemnspopover

NSPopover and adding spacing with NSStatusItem


I am working on a menubar app, that uses NSPopover. I am using the following code to present popover.

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

Issue is this is being present too close to status bar as shown below.

enter image description here

Even if i change the rect it does not have any effect and rightly so, as the documentation states

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.

Following is the screenshot from dropbox app, was just wondering how can i add some spacing in my app like dropbox.

enter image description here


Solution

  • To achieve this i added a padding view and attach set NSStatusItem View to that container view. Code from the solution used is as follow for anybody looking to implement it.

    _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];