UIPanGestureRecogniser无法正常工作

时间:2015-11-10 18:21:35

标签: ios swift uipangesturerecognizer

我有这个功能来处理拖动视图:+

func handlePan(recognizer:UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)



    let newCenter = CGPointMake(self.view.bounds.size.width / 2,
        recognizer.view!.center.y + translation.y)

    print("the translation x:\(translation.x) & y:\(newCenter.y)")

    if (newCenter.y >= 397 && newCenter.y <= 632) {
        recognizer.view!.center = newCenter


        recognizer.setTranslation(CGPointZero, inView: self.view)
    }


}

立场是正确的。 但是,我需要移动的视图经常在我拖动时阻塞,所以我需要停止并再次开始拖动它。

我该如何解决这个问题?

编辑:我的代码现在看起来像这样,但我仍然遇到了问题:

func handlePan(recognizer:UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)


        switch recognizer.state {
            case .Ended:fallthrough
            case .Changed:

                let newCenter = CGPointMake(self.view.bounds.size.width / 2,
                    recognizer.view!.center.y + translation.y)

                print("the translation x:\(translation.x) & y:\(newCenter.y)")

                if (newCenter.y >= 397 && newCenter.y <= 632) {
                    recognizer.view!.center = newCenter
                    recognizer.setTranslation(CGPointZero, inView: self.view)}

            default : break }


}

1 个答案:

答案 0 :(得分:0)

由于我不知道代码的其他部分,所以这是一个假设你的内容可能应该是什么样的部分:

class ViewController: UIViewController {

// Gesture function
func panAround(recognizer: UIPanGestureRecognizer) {
    switch recognizer.state {
    ...
    case .Changed:
        let translation = recognizer.translationInView(yourView)
        let newCenter = CGPointMake(self.view.bounds.size.width / 2,
                recognizer.view!.center.y + translation.y)

        print("the translation x:\(translation.x) & y:\(newCenter.y)")

        if (newCenter.y >= 397 && newCenter.y <= 632) {
            recognizer.view!.center = newCenter

            // Updating the UI whenever there is a "small change"
            updateUI()

            recognizer.setTranslation(CGPointZero, inView: self.view)
        }
    ...
    }
}

private func updateUI() {
    yourView.setNeedsDisplay()
}

注意:上面的代码不会直接通过复制和粘贴工作,我只是指出你可以在哪里进行调整。