我已经在图像上实现了拖动效果,但是在我的测试中,我看到图像只在单击鼠标事件时移动。
我不能通过拖动事件在屏幕上用鼠标移动图像。但是当我点击屏幕的一侧时,图像就会出现在我点击的地方。
我在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];
}
如果你想拖拽一个图像视图,你会所以使用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];
}
}
您在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];
}
对于其他人,我以这种方式实现了我的问题:
- (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];
}
再次感谢你,马特!