Use UIPanGestureRecognizer to drag UIView inside limited area

放肆的年华 提交于 2020-01-10 20:11:52

问题


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.

What am I missing here ?


回答1:


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)
        }



回答2:


It's a very simple function that just checks if the given point is inside some area on the screen you define:

static func insideDraggableArea(point : CGPoint) -> Bool {
    return point.x > 50 && point.x < 200 &&
           point.y > 20 && point.y < 400
}


来源:https://stackoverflow.com/questions/28938135/use-uipangesturerecognizer-to-drag-uiview-inside-limited-area

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!