当用户在屏幕上移动图形时,我在屏幕上创建了动态图像,但我的问题是当用户触摸屏幕图像上的任何地方时移动到该药水。
这是我的代码:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *mytouch = [[event allTouches] anyObject];
_img.center = [mytouch locationInView:self.view];
}
我想要的是仅在用户点击图像时才移动图像。
答案 0 :(得分:0)
touchesBegan
中的确保触摸位于图片的视图中(我假设_img
的类型为UIImageView
):
-(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
是否包含给定的CGRect
(在这种情况下是图像的帧)
然后在touchesMoved
:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *mytouch = [[event allTouches] anyObject];
if (_imageTouched) {
_img.center = [mytouch locationInView:self.view];
}
}
并且不要忘记在touchesEnd方法中将_imageTouched
设置为NO
。