iOS:拖动效果不正常

时间:2013-04-16 18:01:01

标签: ios objective-c uiviewcontroller

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

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

我在youtube上关注了很多主题,但最后,我的行为并不相同。

这是我的代码:

ScreenView1.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];
}

3 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分: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];
}

答案 2 :(得分: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];

}
再次感谢Matt!