Use UIPanGestureRecognizer to drag UIView inside limited area

前端 未结 2 599
臣服心动
臣服心动 2021-01-03 11:15

I want to allow user to drag UIView inside a limited area of its super view. Trying the following simple code:

func handlePanForImage(recognizer: UIPanGestur         


        
相关标签:
2条回答
  • 2021-01-03 11:36

    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)
            }
    
    0 讨论(0)
  • 2021-01-03 11:52

    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
    }
    
    0 讨论(0)
提交回复
热议问题