0

我已经在图像上实现了拖动效果,但在测试期间,我看到图像仅在单击鼠标事件时移动。

我无法通过拖动事件在屏幕上使用鼠标移动图像。但是当我点击屏幕的一侧时,图像会占据我点击的位置。

我在 youtube 上关注了许多主题,但最后,我没有相同的行为。

这是我的代码:

屏幕视图1.h

IBOutlet UIImageView *image;

ScreenView1.m

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    image.center = location;
    [self ifCollision];
}

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [self touchesBegan:touches withEvent:event];
}
4

3 回答 3

2

如果你想拖动一个图像视图,使用 UIPanGestureRecognizer 会更开心它使这种事情变得微不足道。使用touchesBegan是如此 iOS 4 !

UIPanGestureRecognizer* p =
    [[UIPanGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(dragging:)];
[imageView addGestureRecognizer:p];

// ...

- (void) dragging: (UIPanGestureRecognizer*) p {
    UIView* vv = p.view;
    if (p.state == UIGestureRecognizerStateBegan ||
            p.state == UIGestureRecognizerStateChanged) {
        CGPoint delta = [p translationInView: vv.superview];
        CGPoint c = vv.center;
        c.x += delta.x; c.y += delta.y;
        vv.center = c;
        [p setTranslation: CGPointZero inView: vv.superview];
    }
}
于 2013-04-16T18:05:10.683 回答
0

您在 中没有做正确的事情touchesMoved:withEvent:,这就是拖动不起作用的原因。这是一个有效的小代码:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    [CATransaction begin];
    [CATransaction setDisableActions:YES];
    [image setCenter:location];
    [CATransaction commit];
}
于 2013-04-16T18:06:10.400 回答
0

对于其他人,我以这种方式实现了我的问题:

- (IBAction)catchPanEvent:(UIPanGestureRecognizer *)recognizer{
    CGPoint translation = [recognizer translationInView:self.view];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                         recognizer.view.center.y + translation.y);

    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];

}

再次感谢马特!

于 2013-04-16T19:54:17.950 回答