使用UIPanGestureRecognizer在有限区域内拖动UIView [英] Use UIPanGestureRecognizer to drag UIView inside limited area
本文介绍了使用UIPanGestureRecognizer在有限区域内拖动UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想允许用户将UIView拖动到其超级视图的有限区域内。尝试以下简单代码:
I want to allow user to drag UIView inside a limited area of its super view. Trying the following simple code:
func handlePanForImage(recognizer: UIPanGestureRecognizer) {
if let myView = recognizer.view {
switch (recognizer.state) {
case .Changed:
let translation = recognizer.translationInView(self)
if insideDraggableArea(myView.center) {
myView.center = CGPoint(x:recognizer.view!.center.x + translation.x, y:recognizer.view!.center.y + translation.y)
recognizer.setTranslation(CGPointZero, inView: self)
}
default:
break
}
}
}
我看到确实没有将视图拖到有限区域之外,但是当我尝试再次将其从他的最后一个有效位置拖动。
I see that indeed the view is not dragged outside the limited area, however when I try to drag it again from his last valid position nothing happens.
我在这里错过了什么?
推荐答案
解释在其他一些帖子中,我首先需要计算新位置,然后检查新位置是否在范围内,并且只有在更新视图的坐标时才可以:
As explain in some other posts, I needed first to compute the new location, then check if the new location is inside the bounds, and only if it is update the view's coordinates:
let translation = recognizer.translationInView(self)
let newPos = CGPoint(x:recognizer.view!.center.x + translation.x, y:recognizer.view!.center.y + translation.y)
if insideDraggableArea(newPos) {
myView.center = newPos
recognizer.setTranslation(CGPointZero, inView: self)
}
这篇关于使用UIPanGestureRecognizer在有限区域内拖动UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文