在屏幕IOS上移动图像?

时间:2014-12-23 16:30:02

标签: ios objective-c

当用户在屏幕上移动图形时,我在屏幕上创建了动态图像,但我的问题是当用户触摸屏幕图像上的任何地方时移动到该药水。

这是我的代码:

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

我想要的是仅在用户点击图像时才移动​​图像。

1 个答案:

答案 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