我们平时开发中NSWindow
有个方法是可以设置点击窗口背景拖动窗口的,就是下面的这个方法,使用起来也比较方便,可是有个问题就是随着项目的层级关系越来越多,越来越复杂,上层的视图有各种各样的事件要相应的时候有必要自定义一个拖动视图,需要的地方允许用户拖动窗口,增加用户体验,我的就是层级太多了可以拖动的区域都被盖住了导致单独实现这个功能的
self.window.movable = YES;
[self.window setMovableByWindowBackground:YES];
实现一个基类,封装进去
#import "SHView.h"
@interface SHView ()
@property (nonatomic , assign) NSPoint oldPoint;
@end
@implementation SHView
- (BOOL)mouseDownCanMoveWindow
{
[super mouseDownCanMoveWindow];
return YES;
}
- (void)updateTrackingAreas
{
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:(NSTrackingEnabledDuringMouseDrag|NSTrackingActiveInActiveApp|NSTrackingInVisibleRect|NSTrackingAssumeInside|NSTrackingCursorUpdate)owner:self userInfo:nil];
[self addTrackingArea:trackingArea];
}
- (void)mouseDown:(NSEvent *)event
{
[super mouseDown:event];
self.oldPoint = event.locationInWindow;
}
- (void)mouseDragged:(NSEvent *)event
{
NSPoint screenPoint = [self.window convertPointToScreen:event.locationInWindow];
NSPoint newPoint = NSMakePoint(screenPoint.x-self.oldPoint.x, screenPoint.y-self.oldPoint.y);
[self.window setFrameOrigin:newPoint];
}
代码量不太多,主要流程如下
- 允许点击背景拖动窗口,跟当前功能无关,在简单的页面使用系统的拖动功能设置的
- 添加拖动监听
- 点击时保存当前坐标在窗口的位置
- 根据点击的初始坐标和拖动的偏移量计算出当前窗口的坐标,更改当前窗口的坐标
网友评论