2011-02-12 69 views
8

我想點擊一個UIView並拖動並使該視圖跟隨我的手指,很簡單。但最簡單的方法是將對象的中心設置爲水龍頭髮生的位置(這不是我想要的),我希望它移動,就好像您在任何地方抓住對象一樣。在手指下拖動UIView

有一個非常有用的方法來做到這一點,它是一個iTunes U視頻中的參考。該腳本沒有使用deltaX,deltaY來拖動下面的圖像,而不是將它放在手指下方,但我不記得那個代碼是什麼!

有沒有人有此代碼的參考?或者,也許有一種不用uiview.center = tap.center概念就可以在手指下移動UIViews的有效方式?

+1

請問答案幫幫我?如果是這樣,請檢查它是否正確或否則回覆... – TigerCoding 2011-02-12 21:13:55

+0

他沒有回覆 - 這不是他想要的。 – xil3 2011-08-12 19:02:01

+0

有沒有找到解決辦法?我會好奇的看到一個沒有使用三角洲的,因爲你聲稱看到。 – sean 2013-03-12 15:54:25

回答

0

我想你所談論的死纏爛打應用...

// Tell the "stalker" rectangle to move to each touch-down 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [UIView beginAnimations:@"stalk" context:nil]; 
    [UIView setAnimationDuration:1]; 
    //[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
    [UIView setAnimationBeginsFromCurrentState:YES]; 

    // touches is an NSSet. Take any single UITouch from the set 
    UITouch *touch = [touches anyObject]; 

    // Move the rectangle to the location of the touch 
    stalker.center = [touch locationInView:self]; 
    [UIView commitAnimations]; 
} 
+1

感謝您的代碼,但這不是我想要完成的。我想讓物體在我的手指下移動,因爲我拖動的時候,UIView的中心會根據我的手指移動而不是集中在我的手指上而移動 – Parad0x13 2011-02-12 23:37:54

+1

@ Parad0x13嘿,你有沒有解決問題的方法?那麼請讓我知道,因爲我面臨同樣的情況,我需要解決它。 – 2015-02-24 04:51:35

0

可以節省在那裏你觸摸的點(T)和視圖的當前位置(O)。在touchMoved中,您可以通過添加(O-T)基於新點移動它。

6

以下是Apple的MoveMe項目的代碼,關鍵是在touchesMoved方法中執行此操作。它允許UIViewPlacardView)看到觸摸並移動到用戶的任何觸摸位置。希望這可以幫助。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 

UITouch *touch = [touches anyObject]; 

// If the touch was in the placardView, move the placardView to its location 
if ([touch view] == placardView) { 
    CGPoint location = [touch locationInView:self]; 
    placardView.center = location; 
    return; 
    } 
} 
9

以下代碼是允許面板/視圖移動的簡單手勢識別器的示例。不是修改中心,而是修改原點[基本上通過設置目標視圖的新框架]。

所以你不必深入到gesture.view您可以在您的情況優化這個...等

-(void)dragging:(UIPanGestureRecognizer *)gesture 
{ 
    if(gesture.state == UIGestureRecognizerStateBegan) 
    { 
     //NSLog(@"Received a pan gesture"); 
     self.panCoord = [gesture locationInView:gesture.view]; 


    } 
    CGPoint newCoord = [gesture locationInView:gesture.view]; 
    float dX = newCoord.x-panCoord.x; 
    float dY = newCoord.y-panCoord.y; 

gesture.view.frame = CGRectMake(gesture.view.frame.origin.x+dX, gesture.view.frame.origin.y+dY, gesture.view.frame.size.width, gesture.view.frame.size.height); 
} 

斯威夫特4:

@objc func handleTap(_ sender: UIPanGestureRecognizer) { 
     if(sender.state == .began) { 
      self.panCoord = sender.location(in: sender.view) 
     } 

     let newCoord: CGPoint = sender.location(in: sender.view) 

     let dX = newCoord.x - panCoord.x 
     let dY = newCoord.y - panCoord.y 

     sender.view?.frame = CGRect(x: (sender.view?.frame.origin.x)!+dX, y: (sender.view?.frame.origin.y)!+dY, width: (sender.view?.frame.size.width)!, height: (sender.view?.frame.size.height)!) 
    }