如何以编程方式创建NSView以便用户可以使用鼠标移动其位置?我需要为视图分配哪些属性?谢谢!
newView = [helpWindow contentView];
[contentView addSubview:newView];
//add properties of newView to be able to respond to touch and can be draggable
答案 0 :(得分:2)
不幸的是,没有像setMoveByWindowBackground那样的简单方法:你可以用窗口做。您必须覆盖mouseDown:,mouseDragged:和mouseUp:并使用setFrameOrigin:基于鼠标指针的位置。为了在第一次单击内部时没有视图跳转,您还需要考虑视图的原点与第一次单击时moue指针在视图中的位置之间的偏移。这是我在一个项目中制作的一个例子,用于在父视图中移动“图块”(这是用于游戏“Upwords”的计算机版本,就像3d拼字游戏一样)。
-(void)mouseDown:(NSEvent *) theEvent{
self.mouseLoc = [theEvent locationInWindow];
self.movingTile = [self hitTest:self.mouseLoc]; //returns the object clicked on
int tagID = self.movingTile.tag;
if (tagID > 0 && tagID < 8) {
[self.viewsList exchangeObjectAtIndex:[self.viewsList indexOfObject:self.movingTile] withObjectAtIndex: 20]; // 20 is the highest index in the array in this case
[self setSubviews:self.viewsList]; //Reorder's the subviews so the picked up tile always appears on top
self.hit = 1;
NSPoint cLoc = [self.movingTile convertPoint:self.mouseLoc fromView:nil];
NSPoint loc = NSMakePoint(self.mouseLoc.x - cLoc.x, self.mouseLoc.y - cLoc.y);
[self.movingTile setFrameOrigin:loc];
self.kX = cLoc.x; //this is the x offset between where the mouse was clicked and "movingTile's" x origin
self.kY = cLoc.y; //this is the y offset between where the mouse was clicked and "movingTile's" y origin
}
}
-(void)mouseDragged:(NSEvent *)theEvent {
if (self.hit == 1) {
self.mouseLoc = [theEvent locationInWindow];
NSPoint newLoc = NSMakePoint(self.mouseLoc.x - self.kX, self.mouseLoc.y - self.kY);
[self.movingTile setFrameOrigin:newLoc];
}
}
这个例子指出了另一种可能的并发症。当你移动一个视图时,它可能看起来在其他视图下移动,所以我注意到我将移动视图作为父视图子视图的最顶层视图(viewsList是从self.subviews获取的数组)