我正在尝试创建一个可拖动的图像,但我试图限制它拖动到一个小方块而不是全屏。有人能告诉我哪里出错了吗?我已经放置了目前为止的代码:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([touch view] == dot) {
CGPoint location = [touch locationInView:self.view];
dot.center = location;
if (location.x >10) {
location.x =10;
} else if (location.x <10) {
location.x = 10;
}
if (location.y >20) {
location.y =20;
} else if (location.y < 20) {
location.y = 20;
}
}
}
答案 0 :(得分:3)
您在对其进行更改之前指定location
。
首先将限制应用于location
,然后将其分配给dot
。
此外,您显示的限制会将您的位置锁定为10,20,因为您不允许它超过10或小于10.与20相同。
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([touch view] == dot) {
CGPoint location = [touch locationInView:self.view];
location.x = MIN(MAX(location.x, 0),10);
location.y = MIN(MAX(location.y, 0),20);
dot.center = location;
}
}
答案 1 :(得分:1)
我最近像这样实现了图像拖动功能。我使用PAN手势移动图像,导致两个CGFloats“endPointX和endPointY”。在下面的代码“保持屏幕检查”和“屏幕上的结束检查”之间的代码中,我检查这些是否在屏幕上。如果不是,我调整它们以防止图像移出屏幕。
我希望有所帮助。如果你想在整个屏幕的一小部分内移动图像,那么我会将图像添加到持有者子视图中,然后检查上面的持有者视图.bounds.size.width / height。
CGFloat endPointX = translatedPoint.x + (.35*[(UIPanGestureRecognizer*)sender
velocityInView:self.view].x);
CGFloat endPointY = translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);
// Stay on the screen check
if(endPointX < 0) {
endPointX = 0;
} else if(endPointX > self.view.bounds.size.width) {
endPointX = self.view.bounds.size.width;
}
if(endPointY < 0) {
endPointY = 0;
} else if(endPointY > self.view.bounds.size.height) {
endPointY = self.view.bounds.size.height;
}
// End of the Stay on Screen check
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.35];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[[sender view] setCenter:CGPointMake(endPointX, endPointY)];
[UIView commitAnimations];