NSPopOver & NSViewController - drag and drop to resize

I am creating a MenuBar app that I am using NSPopOver

. The problem is that, NSPopover uses NSViewController as a contentViewController

whose size is fixed. My requirement is to make the size of the NSViewController flexible, just like NSWindowController

(setting the minimum size and maximum size depends on the overall screen size). In simple words, how to resize NSViewController (NSPopOver) when the user drags it. I am new to OS X programming.


source to share

2 answers

I finally got started using Mouse Events

. You just need to watch out

override func mouseDown(theEvent: NSEvent) {}
override func mouseDragged(theEvent: NSEvent) {}


and reset the size of the popOver content. Hope this would be helpful to someone one day.


override func mouseDragged(theEvent: NSEvent) {
        var currentLocation = NSEvent.mouseLocation()
        println("Dragged at : \(currentLocation)")

        var newOrigin   = currentLocation
        let screenFrame = NSScreen.mainScreen()?.frame
        var windowFrame = self.view.window?.frame

        newOrigin.x     = screenFrame!.size.width - currentLocation.x
        newOrigin.y     = screenFrame!.size.height - currentLocation.y

        println("the New Origin Points : \(newOrigin)")

        // Don't let window get dragged up under the menu bar
        if newOrigin.x < 450 {
            newOrigin.x = 450

        if newOrigin.y < 650 {
            newOrigin.y = 650

        println("the New Origin Points : \(newOrigin)")

        let appDelegate : AppDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.popover.contentSize = NSSize(width: newOrigin.x, height: newOrigin.y)



This is how I tracked the mouse event. On the mouse, drag only the current position and the new position (up to the point where the user dragged) and then checked if the point is less than my default size for Popover ie (450, 650) in this case. Once the point has been calculated, simply set the size of the popover.

This is just a suggested method. There must be something better then, but for now this is what I have done.



Here is an answer that only handles vertical but not horizontal NSPopover resizing.

    override func mouseDragged(with theEvent: NSEvent) {
        let currentLocation = NSEvent.mouseLocation()
        let screenFrame = NSScreen.main()?.frame

        var newY = screenFrame!.size.height - currentLocation.y

        if newY < MIN_HEIGHT {
            newY = MIN_HEIGHT

        if newY > MAX_HEIGHT {
            newY = MAX_HEIGHT

        let appDelegate : AppDelegate = NSApplication.shared().delegate as! AppDelegate
        appDelegate.popover.contentSize = NSSize(width: FIXED_WIDTH, height: newY)





All Articles