Popover from Separate XIB File

I’m going to need to display the same popover from many different subviews. I don’t want to have to duplicate the custom view etc in every view XIB so I added a XIB that just contains the resources needed for the popover. In this simple non-Document-based app the AppDelegate is the File’s owner for both the app’s XIB and also for the popover’s:

class AppDelegate: NSObject, NSApplicationDelegate {

	@IBOutlet weak var window: NSWindow!
	@IBOutlet var popoverView: NSPopover!

	func applicationDidFinishLaunching(aNotification: NSNotification) {
		let loaded = NSBundle.mainBundle().loadNibNamed("PopoverView", 
				owner: self, topLevelObjects: nil)
		print("Loaded Nib: \(loaded)")

Note that the IBOutlet above is not ‘weak’. You need this to keep the data resident.

As far as the XIB itself, I added a “View” “User Interface” file. In this XIB, the File’s Owner class is set to AppDelegate. Added a “Popover and View Controller” and connected the XIB’s view to the Popover View Controller’s ‘view’ outlet. Added an IBAction in the App Delegate:

	@IBAction func ShowPopover(sender: NSView) {
		popoverView.showRelativeToRect(sender.bounds, ofView: 
				sender, preferredEdge: NSRectEdge.MinX)

The popoverView is connected to the File’s Owner in IB. Do whatever way you need to invoke the ShowPopover action — I used a button. I may have forgotten something, but that’s pretty much it.

Leave a Reply

Your email address will not be published. Required fields are marked *