从 macOS 10.11 开始,最简单的方法是使用新-[NSWindow performWindowDragWithEvent:]
方法:
@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
在这里,-performWindowDragWithEvent:
将处理不重叠菜单栏的正确行为,并且还将在 macOS 10.12 及更高版本上对齐边缘。确保在视图的私有接口中包含一个实例变量,这样一旦确定不想处理事件,BOOL movingWindow
就可以避免事件。-mouseDragged:
在这里,我们还检查-[NSWindow movableByWindowBackground]
设置为YES
以便此视图可以在不可移动的按窗口背景窗口中使用,但这是可选的。