Swift – Move a NSWindow by dragging a NSView

cocoamacosnsviewnswindowswift

I have a NSWindow, on which i apply this:

window.styleMask = window.styleMask | NSFullSizeContentViewWindowMask
window.titleVisibility = NSWindowTitleVisibility.Hidden;
window.titlebarAppearsTransparent = true;

I then add a NSView behind the titlebar to simulate a bigger one.
Now it looks like this:
Current window

I want to be able to move the window, by dragging the light-blue view. I have already tried to subclass NSView and always returning true for mouseDownCanMoveWindow using this code:

class LSViewD: NSView {
    override var mouseDownCanMoveWindow:Bool {
        get {
            return true
        }
    }
}

This didn't work.
After some googling i found this INAppStoreWindow on GitHub. However it doesn't support OS X versions over 10.9, so it's completely useless for me.

Edit1

This is how it looks in the Interface Builder.
Interface Builder

How can i move the window, by dragging on this NSView?

Best Answer

None of the answers here worked for me. They all either don't work at all, or make the whole window draggable (note that OP is not asking for this).

Here's how to actually achieve this:

To make a NSView control the window with it's drag events, simply subclass it and override the mouseDown as such:

class WindowDragView: NSView {

    override public func mouseDown(with event: NSEvent) {
        window?.performDrag(with: event)
    }

}

That's it. The mouseDown function will transfer further event tracking to it's parent window.

No need for window masks, isMovableByWindowBackground or mouseDownCanMoveWindow.

Related Topic