2014-12-23 227 views
-1

我在屏幕上創建了移動圖像,當用戶在移動的屏幕上移動圖形時,但是我的問題是當用戶觸摸屏幕圖像上的任何位置移動到該藥水時。在屏幕IOS上移動圖像?

這是我的代碼:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *mytouch = [[event allTouches] anyObject]; 
    _img.center = [mytouch locationInView:self.view]; 
} 

我想要的是移動影像,只有當圖像用戶點擊屏幕上的任何地方沒有。

+0

觸摸開始行動,你應該檢查是圖像幀包括用戶觸摸點。 –

回答

0
touchesBegan

確保觸摸是圖像的視圖內(I假設_imgUIImageView類型):

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *mytouch = [[event allTouches] anyObject]; 
    CGPosition touchPosition = [mytouch locationInView:self.view]; 

    if (CGRectContainsPoint(_img.frame, touchPosition) && [touches count] == 1) { 
     _imageTouched = YES; // Declare _imageTouched in your class for this to work 
    } 
} 

CGRectContainsPoint測試如果給定CGPoint被withing給定CGRect(這是圖像的幀中這種情況下)

然後在touchesMoved

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *mytouch = [[event allTouches] anyObject]; 
    if (_imageTouched) { 
     _img.center = [mytouch locationInView:self.view]; 
    } 
} 

並且不要忘記在touchesEnd方法中設置_imageTouchedNO

+0

好的,謝謝它的作品。 – LanWanMan