我有一个拼图类型的应用程序,用户可以拾取40个拼图中的任何一个并将它们拖到屏幕上。在测试中,我注意到有些用户不小心将这些碎片掉到了屏幕边界之外,无法检索到这些碎片。
如何指定不能将视图移动到视图范围之外?
谢谢。
答案 0 :(得分:2)
我倾向于采用一种策略,当触摸结束时,我会检查所讨论的CGRect的边界是否在superview的rect之外。如果是,那么我将其动画回到视图中。
我不确定这是如何实现的,因为我通常使用UIPanGestureRecognizer来处理这些类型的行为,这些行为允许我访问正在移动的视图对象。话虽这么说,如果视图对象是一个ivar,它看起来像这样。
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//note: pieceView is your ivar for the view being moved.
CGRect screenRect = [[UIScreen mainScreen] bounds];
void(^animationBlock)(void);
if ((pieceView.frame.origin.x + pieceView.frame.size.width) > screenRect.size.width) { //outside right side
animationBlock = ^{
int newXVal = (screenRect.size.width - (pieceView.frame.size.width/2));
pieceView.center = CGPointMake(newXVal, pieceView.center.y);
};
}
else if (pieceView.frame.origin.x < 0.0f) { //outside left side
animationBlock = ^{
int newXVal = -(pieceView.frame.size.width/2);
pieceView.center = CGPointMake(newXVal, pieceView.center.y);
};
}
else if ((pieceView.frame.origin.y + pieceView.frame.size.height) > screenRect.size.height) { //outside bottom
animationBlock = ^{
int newYVal = (screenRect.size.height - (pieceView.frame.size.height/2));
pieceView.center = CGPointMake(pieceView.center.x, newYVal);
};
}
else if (pieceView.frame.origin.y < 0.0f) { //outside top
animationBlock = ^{
int newYVal = -(pieceView.frame.size.height/2);
pieceView.center = CGPointMake(pieceView.center.x, newYVal);
};
}
[UIView animateWithDuration:0.2 animations:animationBlock];
}
如果您最终使用UIPanGestureRecognizer,则可以通过访问平移手势识别器的视图属性来访问您正在移动的视图。