如何允许在某些区域拖动UIView(PanGesture ..)

时间:2015-08-13 14:57:50

标签: ios xcode swift uiview uipangesturerecognizer

我需要通过PanGestureRecognizer拖动UIView(我知道怎么做),但我无法弄清楚,如何限制它。从顶部需要一些填充,如果与四个边之一(左边,右边,顶部(这里是填充)和设备底部)发生碰撞,请停止拖动,你不能覆盖 - 或者像1xx填充一样顶部,无论如何。 :)

我试过这个:https://github.com/andreamazz/UIView-draggable但如果我通过cagingArea设置了限制区域,则iPad(Air)会滞后。移动也不顺畅,我认为原生PanGestureRecognizer是最好的,只需要限制区域,你知道我该怎么做吗? :)

我在Swift写作。并且还找到了一些相关的主题,比如这个 - > Use UIPanGestureRecognizer to drag UIView inside limited area但我不知道insideDraggableArea在做什么?

非常感谢程序员!

3 个答案:

答案 0 :(得分:3)

我在项目中遇到的同样问题, 试试这个,

1)Init PanGesture

let panRec = UIPanGestureRecognizer()

2)将PanGesture添加到你的UIView

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

3)设置draggedView功能的限制

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

答案 1 :(得分:0)

你必须使用UIPanGestureRecognizer吗? 将视图添加到viewcontroller并检查是否启用了用户交互。 我认为你应该标记视图并使用touchesMoved方法。

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

答案 2 :(得分:0)

这对我有用:

guard let view = UIApplication.shared.windows.last else { return }
view.addSubview(customView)