Allow click and dragging a view to drag the window itself?

后端 未结 8 1753
醉梦人生
醉梦人生 2020-12-29 06:06

I\'m using a textured window that has a tab bar along the top of it, just below the title bar.

I\'ve used -setContentBorderThickness:forEdge: on the window to make t

8条回答
  •  借酒劲吻你
    2020-12-29 06:36

    As of macOS 10.11, the simplest way to do this is to utilize the new -[NSWindow performWindowDragWithEvent:] method:

    @interface MyView () {
        BOOL movingWindow;
    }
    @end
    
    @implementation MyView
    
    ...
    
    - (BOOL)mouseDownCanMoveWindow
    {
        return NO;
    }
    
    - (void)mouseDown:(NSEvent *)event
    {
        movingWindow = NO;
    
        CGPoint point = [self convertPoint:event.locationInWindow
                                  fromView:nil];
    
        // The area in your view where you want the window to move:
        CGRect movableRect = CGRectMake(0, 0, 100, 100);
    
        if (self.window.movableByWindowBackground &&
            CGRectContainsPoint(movableRect, point)) {
    
            [self.window performWindowDragWithEvent:event];
            movingWindow = YES;
            return;
        }
    
        // Handle the -mouseDown: as usual
    }
    
    - (void)mouseDragged:(NSEvent *)event
    {
        if (movingWindow) return;
    
        // Handle the -mouseDragged: as usual
    }
    
    @end
    

    Here, -performWindowDragWithEvent: will handle the correct behavior of not overlapping the menu bar, and will also snap to edges on macOS 10.12 and later. Be sure to include a BOOL movingWindow instance variable with your view's private interface so you can avoid -mouseDragged: events once you determined you don't want to process them.

    Here, we are also checking that -[NSWindow movableByWindowBackground] is set to YES so that this view can be used in non-movable-by-window-background windows, but that is optional.

提交回复
热议问题