你必須使用以下方法:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
//...
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
//..
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
//...
}
中的touchesBegan方法
,檢查觸摸是你的形象:
if (CGRectContainsPoint(yourImage.frame, touchLocation)){
dragging = YES;
}
如果是的話設置一個全局變量,例如bool拖動到YES。
在touchesMoved:
檢查
if (dragging){
yourImage.frame = CGRectMake(touchLocation.x, touchLocation.y,yourImage.frame.size.widht,yourImage.frame.size.height);
}
在touchesEnded
: 組拖到NO
拖動= NO;
所以:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(yourImage.frame, touchLocation)){
dragging = YES;
[timer invalidate];
timer = nil;
}
//...
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (dragging){
yourImage.frame = CGRectMake(touchLocation.x, touchLocation.y,yourImage.frame.size.widht,yourImage.frame.size.height);
}
//..
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
dragging = NO;
//...
}
我將如何阻止它?我試圖在觸摸開始時使計時器無效,但它仍然無效 – user2838188
使用標誌來檢查是否可以在觸摸處理代碼中移動圖像視圖和更改標誌值。 –
嘗試使計時器無效或使其無效..它應該工作 –