Sep*_*nic 5 cocoa-touch user-interaction uiimageview
我正在尝试为我的imageView(下面的代码中的maskPreview)创建移动功能,以便用户可以在屏幕周围移动maskPreview中包含的图片.这是触摸开始和触摸移动的代码:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([touches count]==1) {
UITouch *touch= [touches anyObject];
originalOrigin = [touch locationInView:maskPreview];
}
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if ([touches count]==1) {
UITouch *touch = [touches anyObject];
CGPoint lastTouch = [touch previousLocationInView:self.view];
CGFloat movedDistanceX = originalOrigin.x-lastTouch.x;
CGFloat movedDistanceY = originalOrigin.y-lastTouch.y;
[maskPreview setFrame:CGRectMake(maskPreview.frame.origin.x+movedDistanceX, maskPreview.frame.origin.y + movedDistanceY, maskPreview.frame.size.width, maskPreview.frame.size.height)];
}
}
Run Code Online (Sandbox Code Playgroud)
但我从应用程序得到一些奇怪的回应.我没有限制图像视图可以移动多远,即防止它移出屏幕,但即使这是一个小动作,我的图像视图也会疯狂消失.
非常感谢所有的帮助
touchesBegan在这个现代世界中,实施等等是过度的.你只是混淆了自己,你的代码将很快变得无法理解或维护.使用UIPanGestureRecognizer; 这就是它的用途.使用UIPanGestureRecognizer进行可拖动视图是微不足道的.这是UIPanGestureRecognizer的动作处理程序,它使视图可拖动:
- (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];
}
}
Run Code Online (Sandbox Code Playgroud)