Swift - Rotate gesture and rotation increments of 90 degrees

只谈情不闲聊 提交于 2019-12-07 23:58:36

I achieved this by implementing it as follows:

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

Note that I added the UIRotationGestureRecognizer on the desired view from the Interface Builder, that's why the function is an @IBAction.

Output:

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