我有一个带有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>
输出:
关于Swift - 旋转手势和 90 度的旋转增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959523/