我是Mac上Cocoa开发的新手,我在创建可拖动的NSView子类时遇到了问题,尽管我已经遵循了许多不同的指南,包括the main Apple docs on custom views。
到目前为止我执行的代码是:
-(void)mouseDown:(NSEvent *) e {
[[NSCursor closedHandCursor] push];
self.lastDragLocation = [e locationInWindow];
}
-(void)mouseDragged:(NSEvent *)event {
NSView* superView = [self superview];
NSPoint currentOrigin = self.lastDragLocation;
NSRect currentFrame = [self frame];
NSPoint nextOrigin = NSMakePoint(currentOrigin.x + [event deltaX],
currentOrigin.y + ([event deltaY] *
([superView isFlipped] ? 1 : -1))
);
[self setFrameOrigin:nextOrigin];
[self autoscroll:event];
[superView setNeedsDisplayInRect:NSUnionRect(currentFrame, [self frame])];
self.lastDragLocation = nextOrigin;
}
-(void)mouseUp:(NSEvent*)event {
[NSCursor pop];
[[self window] invalidateCursorRectsForView:self];
}
当我拖动视图时,一切似乎都有效,但当我停止移动或释放鼠标时,视图会快速回到原始原点。如果在拖动过程中发生这种情况,后续拖动事件会将视图设置回正确的位置,仅重复此问题。
顺便说一句,这是在Mountain Lion上运行的XCode 5.0。