Swift - 旋转手势和旋转增量90度

时间:2016-06-22 05:48:26

标签: swift rotation gesture pi

我有一个带UIRotationGestureRecognizer的rotateView设置。按预期工作,但我只想以90度的凹口/增量旋转。默认行为允许您在旋转时非常精细和精确。我希望它是相反的,只有4个可能的位置。

我下面的代码尽可能接近,但是我遇到的问题是旋转只发生一次,而且只向一个方向旋转(向右旋转,即使我的2个手指向左旋转)

我的代码

func rotatedView(recognizer:UIRotationGestureRecognizer){
    let pi = CGFloat(M_PI)
    rotateView.transform = CGAffineTransformMakeRotation(pi/2)
    recognizer.rotation = 0
    if recognizer.state == UIGestureRecognizerState.Changed {
        print("rotation began")
    }
    else {
        print("rotation ended")
    }
}

如何根据手势修改上述代码以允许在任一方向上旋转90度?

1 个答案:

答案 0 :(得分:1)

我通过以下方式实现了这一目标:

@IBAction func handleRotation(_ recognizer: UIRotationGestureRecognizer) {
    if let recognizerView = recognizer.view {
        recognizerView.transform = recognizerView.transform.rotated(by: recognizer.rotation)
        recognizer.rotation = 0

        let radians:Double = atan2( Double(recognizerView.transform.b), Double(recognizerView.transform.a))
        let degrees = radians * Double((180 / Float.pi))

        if recognizer.state == .ended || recognizer.state == .cancelled {
            var degreeToAnimate:CGFloat = 0

            switch degrees {
            case -45...45:
                print("the default value 0, no need to any assign...")
            case 46...135:
                degreeToAnimate = CGFloat(M_PI_2)
            case 136...180, -180 ... -136:
                degreeToAnimate = CGFloat(M_PI)
            case -135 ... -46:
                degreeToAnimate = CGFloat(-M_PI_2)
            default:
                print("!")
            }

            UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: {
                recognizerView.transform = CGAffineTransform(rotationAngle: degreeToAnimate)
            }, completion: { _ in
                recognizer.rotation = 0
            })
        }
    }
}

请注意,我在Interface Builder中添加了UIRotationGestureRecognizer所需的视图,这就是函数为@IBAction的原因。

<强>输出:

enter image description here