我不清楚一些自定義變量之類的東西,所以而非調試代碼,我想我會告訴你我會怎麼使用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;
}
}
來源
2012-12-23 18:36:36
Rob
我不承認'frameY','frameHeight','frameOrigin'等。這只是對實際代碼的簡寫(如:'frame.origin.y','frame.size.height' ,「frame.origin」等)。但我同意列維的直覺,認爲這種不平等看起來很落後。我也發現''translation.y'重複添加到'frame.origin.y'令人擔憂。我會使用視圖的原始「原點」(除非您每次都重置翻譯,這是我不會瘋狂的做法)。最後,你將'frame.origin.x'設置爲'self.view.bounds.size.width'的_x_ ......這將它放在屏幕上,不是?你看到任何NSLog? – Rob