2013-04-26 96 views
1

我在UIView中有一些圖像。這是我的代碼:當用戶開始觸摸圖像視圖時移動UIImageView

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *myTouch = [touches anyObject]; 
    CGPoint startPoint = [myTouch locationInView:self]; 
    imageview.center = CGPointMake(startPoint.x, startPoint.y); 
} 

這樣用戶可以點擊屏幕上的任何地方,圖像視圖將傳送到觸摸位置並從那裏移動。我想限制它,以便它只會響應,如果用戶開始點擊圖像瀏覽。 我該怎麼做?

回答

3

我會做一個手勢識別器添加到圖像視圖。如果使用UIPanGestureRecognizer當用戶開始從圖像視圖中拖動,將被解僱,並且可以使用locationOfTouch:inView:方法制定出在哪裏放置拖動圖像視圖

更新更多的細節: 一個UIGestureRecognizer(包含幾個子類的抽象類,或者你可以自己創建)是一個附加到UIView的對象,並且能夠識別手勢(例如,UIPanGestureRecogniser知道用戶正在平移,UISwipGestureRecognizer知道用戶何時滑動)。

你創建一個手勢識別,並將其添加到這樣一個觀點:

UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognizerMethod:)]; 
[self.imageView addGestureRecognizer:panGestureRecognizer]; 

然後在gestureRecognizerMethod實現你可以檢查TEH操作的狀態,並調整圖像視圖的位置

- (void)gestureRecognizerMethod:(UIPanGestureRecognizer *)recogniser 
{ 
    if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) 
    { 
     CGPoint touchLocation = [recognizer locationInView:self.view]; 
     self.imageView.center = touchLocation; 
    } 
} 
+0

可以請給我一個這樣的例子可以做的,我有點新的objective-c ..? – user2325183 2013-04-26 20:44:24

+0

更新了一些更詳細的 – wattson12 2013-04-26 20:50:28

+0

它不工作。當我點擊imageview時,什麼都沒有發生 – user2325183 2013-04-26 21:13:22