SwipeGestureRecognizer 滑动速度超过阈值时调用函数

Call function when SwipeGestureRecognizer swipe speed passes threshold

我目前正在编写一个应用程序,其中包含 UIViewUISwipeGestureRecognizer

我想让识别器识别用户在识别器方向上拖动的速度。当速度足够高(超过特定阈值)时,应该发生自定义操作。和this post里面基本一样,但是我需要写成Swift.

如何将其翻译成 Swift 或者有更好的方法吗?

当前代码,Xcode 错误标记为注释。

接触开始:

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


        //avoid multi-touch gesture
        if(touches.count > 1){
            return;
        }

        if let touch:UITouch = touches.first as? UITouch{
            let locator:CGPoint = touch.locationInView(self.view!)
            start = locator
            startTime = touch.timestamp
        }

触摸结束:

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

    if let touch:UITouch = touches.first as? UITouch{
        let locator:CGPoint = touch.locationInView(self.view!)

        var dx:CGFloat = (locator.x - start!.x);
        var dy:CGFloat = (locator.y - start!.y);
        var magnitude:CGFloat = sqrt(dx*dx+dy*dy)

        if (magnitude >= kMinDistance) {
            // Determine time difference from start of the gesture
            var dt:CGFloat = CGFloat(touch.timestamp - startTime!)
            if (dt > kMinDuration) {
                // Determine gesture speed in points/sec
                var speed:CGFloat = magnitude / dt;
                 if (speed >= kMinSpeed && speed <= kMaxSpeed) {
                    // Swipe detected
                    swipedView()
    }}}}}
var start:CGPoint?
var startTime:NSTimeInterval?

var kMinDistance:CGFloat   = 25.0
var kMinDuration:CGFloat   = 0.1
var kMinSpeed:CGFloat      = 100.0
var kMaxSpeed:CGFloat      = 500.0

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    //avoid multi-touch gesture
    if(touches.count > 1){
        return;
    }

    if let touch:UITouch = touches.first as? UITouch{
        let location:CGPoint = touch.locationInView(self.view!)
        start = location
        startTime = touch.timestamp
    }
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    if let touch:UITouch = touches.first as? UITouch{
        let location:CGPoint = touch.locationInView(self.view!)

        var dx:CGFloat = location.x - start!.x;
        var dy:CGFloat = location.y - start!.y;
        var magnitude:CGFloat = sqrt(dx*dx+dy*dy)

        if (magnitude >= kMinDistance) {
            // Determine time difference from start of the gesture
            var dt:CGFloat = CGFloat(touch.timestamp - startTime!)
            if (dt > kMinDuration) {
                // Determine gesture speed in points/sec
                var speed:CGFloat = magnitude / dt;
                if (speed >= kMinSpeed && speed <= kMaxSpeed) {
                    // Swipe detected
                }
            }
        }
    }
}

老实说,他的还没有经过测试,但我需要一些这样的代码,所以这是在旅途中转换的。

编辑: 经过测试,似乎可以与 Swift 1.2
一起使用 请阅读您问题下方的评论,并阅读 How to Ask 了解您的下一个问题。这次你很幸运,我需要这段代码:)