alagris
alagris

Reputation: 2206

Present popover from NSView

I made a custom CustomView.xib . It is owned by CustomView.swift which subclasses NSView. Now I can easily reuse CustomView inside my Storyboard by just adding NSView and setting it's class to CustomView. The problem is that I have a button inside CustomView.xib and I want to present a popover MyPopoverViewController whenever it's clicked. I googled and found out that in order to present a popover I need to use method like:

presentViewController(viewController: NSViewController, asPopoverRelativeTo: NSRect, of: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior)

The problem is that this method is only available from NSViewController. But I don't have one. I want to trigger popover from within NSView. What should I do now? It should be possible because NSAlert works everywhere and it doesn't even take any NSViewController as an argument. So there should be a way to present popover without ever having any NSViewController.

Upvotes: 2

Views: 1966

Answers (1)

James Bucanek
James Bucanek

Reputation: 3439

That's a convenience method for presenting an existing view controller as a popover.

It sounds like you want to create and present a new popover. To do that, you'll need to create an NSPopover object. This is, effectively, the popover's controller.

Your NSPopover has a contentViewController: NSViewController property, which has a view: NSView property. These are the view controller and view that will get shown in the popover.

How you create these are up to you. You can build them programmatically, but if this is a reusable view imbedded in other nib/storyboard files, I'd suggest defining the popover view and view controller in its own nib file, making the NSPopover object the nib's owner. You'd then present the popover like this (written in Safari):

let popover = NSPopover()
if Bundle.loadNibNamed(nibName: "MyViewPopover", owner: popover, topLevelObjects:nil) {
    ...
    popover.show(relativeTo: view.bounds, of: view, preferredEdge: NSRectEdgeMinX)

Upvotes: 1

Related Questions