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

标签 swift rotation gesture pi

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

我下面的代码是我能得到的最接近的代码,但是我面临的问题是旋转只发生一次,并且只向一个方向旋转(向右旋转,即使我用两根手指向左旋转) .

我的代码

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 度增量?

最佳答案

我通过如下实现实现了这一目标:

@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 中的所需 View 上添加了 UIRotationGestureRecognizer,这就是该函数是 @IBAction 的原因。 p>

输出:

enter image description here

关于Swift - 旋转手势和 90 度的旋转增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959523/

相关文章:

ios - 尝试在触摸开始时向上旋转小鸟,并在触摸结束时向下旋转(SceneKit)

JavaScript - 旋转 Canvas 图像, Angular 被剪掉

ios - 如何在 SwiftUI 中实现触发 switch case 的左或右 DragGesture() ?

ios - 为搜索栏委托(delegate)赋值 - Swift

javascript - 我可以使用旋转功能全天候移动一条线吗?

android - 如何在android模拟器中检测两个手指触摸

android - 在 android 中处理 WebView 内的触摸事件

objective-c - IBDesignable 在 Objective-C 中不起作用

ios - 让菜单从数组的开头开始

ios - Swift:按名称(字符串)按字母顺序将对象数组映射到新数组中的单独字母集合中