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

不羁的心 提交于 2019-12-06 07:16:55

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

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