How to allow drag UIView (PanGesture..) just in some area

吃可爱长大的小学妹 提交于 2019-12-10 10:29:32

问题


I need drag UIView via PanGestureRecognizer (I know how to do), but I can't figure out, how to make it with limitation. Need some padding from top and also if there is collision with one of four sides (left, right, top (here is the padding) and bottom of device) stop the drag and you can't over - or 1px padding like on the top, whatever. :)

I tried this one: https://github.com/andreamazz/UIView-draggable but if I set the area with limitation via cagingArea, iPad (Air) is lagged. Also the moving is not smooth, I think the native PanGestureRecognizer is the best, need just the limitation area, do you know how I can do that please? :)

I'm writing in Swift. And also found some related topics, like this one -> Use UIPanGestureRecognizer to drag UIView inside limited area but I don't know what insideDraggableArea doing?..

Thank you so much programmers!


回答1:


Same problem that I faced in my project, Try this,

1) Init PanGesture

let panRec = UIPanGestureRecognizer()

2) Add PanGesture to your UIView

override func viewDidLoad() {
....
....
panRec.addTarget(self, action: "draggedView:")
yourview.addGestureRecognizer(panRec)
yourview.userInteractionEnabled = true
....
....
}

3) Set your limitation on draggedView function

func draggedView(sender:UIPanGestureRecognizer){
        println("panning")

        var translation = sender.translationInView(self.view)

        println("the translation x:\(translation.x) & y:\(translation.y)")

        //sender.view.
        var tmp=sender.view?.center.x  //x translation
        var tmp1=sender.view?.center.y //y translation

        //set limitation for x and y origin
        if(translation.x <= 100 && translation.y <= 50 )
         {
        sender.view?.center=CGPointMake(tmp!+translation.x, tmp1!+translation.y)
         sender.setTranslation(CGPointZero, inView: self.view)
         }
}



回答2:


Do you have to use UIPanGestureRecognizer ? add view to a viewcontroller and check user interaction enabled. i think you should tag view and use touchesMoved method.

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

    if let touch = touches.first as? UITouch {
        if touch.view.tag == 2 {
            if self.yourView.center.y <= CGFloat(230) { //if you want use limitation drag

                var touchLocation = touch.locationInView(self.view)
                self.yourView.center.y = touchLocation.y
                self.yourView.center.x = touchLocation.x
           }
        }
    }
}


来源:https://stackoverflow.com/questions/31991808/how-to-allow-drag-uiview-pangesture-just-in-some-area

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