2012-04-01 35 views
1

如何以编程方式制作NSView,以便用户可以使用鼠标移动其位置?我需要将哪些属性分配给视图?谢谢!Draggable NSView

newView = [helpWindow contentView]; 
    [contentView addSubview:newView]; 
    //add properties of newView to be able to respond to touch and can be draggable 

回答

2

不幸的是,没有简单的方法,像setMoveByWindowBackground:你可以用一个窗口做。您必须重写mouseDown:,mouseDragged:和mouseUp:并使用setFrameOrigin:根据鼠标指针的位置。为了不在第一次点击时跳过视图跳转,还需要考虑视图的起点与第一次单击时视图中视点指针所在的位置之间的偏移量。这里有一个例子,我在一个项目中在父视图中移动“贴图”(这是针对游戏“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获得的数组)