我不清楚你的一些自定义变量等,所以我没有调试你的代码,我想我会告诉你我如何使用UIPanGestureRecognizer
.
因此,假设 (a) 手势已添加到被拖动的视图中;(b) 该视图包含在您想要约束视图移动的超级视图中,代码可能如下所示:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static CGRect originalFrame;
if (gesture.state == UIGestureRecognizerStateBegan)
{
originalFrame = gesture.view.frame;
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
CGPoint translate = [gesture translationInView:gesture.view.superview];
CGRect newFrame = CGRectMake(originalFrame.origin.x + translate.x,
originalFrame.origin.y + translate.y,
originalFrame.size.width,
originalFrame.size.height);
if (CGRectContainsRect(gesture.view.superview.bounds, newFrame))
gesture.view.frame = newFrame;
}
}
虽然上述内容具有一定的简单性,但我认为我们可以改善用户体验。值得注意的是,如果用户将视图拖到它的超级视图之外,上面的代码将不会做任何事情(例如,拖过左边框并冻结在那里,即使您上下移动手指;不是很优雅)。我认为以下是一个更优雅的用户界面(但阅读代码有点复杂),当用户拖动手指时,我们会将对象拖动到超级视图中与用户的手指是。
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static CGRect originalFrame;
if (gesture.state == UIGestureRecognizerStateBegan)
{
originalFrame = gesture.view.frame;
}
else if (gesture.state == UIGestureRecognizerStateChanged)
{
CGPoint translate = [gesture translationInView:gesture.view.superview];
CGRect newFrame = CGRectMake(fmin(gesture.view.superview.frame.size.width - originalFrame.size.width, fmax(originalFrame.origin.x + translate.x, 0.0)),
fmin(gesture.view.superview.frame.size.height - originalFrame.size.height, fmax(originalFrame.origin.y + translate.y, 0.0)),
originalFrame.size.width,
originalFrame.size.height);
gesture.view.frame = newFrame;
}
}