2012-04-01 63 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獲得的數組)