当用户开始触摸imageview时移动UIImageView



我在UIView中有一些imageview。这是我的代码:

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

这样,用户可以点击屏幕上的任何地方,imageview将传送到触摸位置并从那里移动。我想限制它,使它只会响应,如果用户开始点击imageview。我该怎么做呢?

我会在图像视图中添加一个手势识别器。如果你使用UIPanGestureRecognizer,当用户开始从图像视图内部拖动时,它将被触发,你可以使用locationOfTouch:inView:方法来确定拖动的图像视图的位置

更新更多细节:UIGestureRecognizer(包含几个子类的抽象类,或者你可以自己创建)是一个附加到UIView的对象,并且能够识别手势(例如,uipangesturerecognizer知道用户何时在平移,UISwipGestureRecognizer知道用户何时在滑动)。

创建一个手势识别器并将其添加到如下视图:

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

那么在你的gestureRecognizerMethod实现中,你可以检查手势的状态,并调整图像视图的位置

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

最新更新