Swift-旋转手势,旋转增量为90度 [英] Swift - Rotate gesture and rotation increments of 90 degrees
问题描述
我有一个UIRotationGestureRecognizer
的rotateView设置.可以按预期工作,但是我只想以90度的凹口/增量旋转.默认行为使您可以非常精确地进行旋转.我希望相反,只有4个可能的职位.
I have a rotateView setup with a UIRotationGestureRecognizer
. Works as intended, however I would like to only rotate in notches/increments of 90 degrees. The default behavior allows you to be very granular and precise with the rotation. I want it to be the opposite, of only 4 possible positions.
我下面的代码尽可能地接近我,但是我面临的问题是旋转只发生一次,并且只向一个方向旋转(即使我的两根手指向左旋转,也向右旋转)
The code I have below is as close I could get, however the problem I am facing is the rotation only happens once, and only to one direction (rotates to the right, even if I 2-fingers rotate to the left).
我的代码
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度?
How can I modify the above code to allow for 90 degree rotation increments in either direction based on gesture?
推荐答案
我是通过以下方式实现的:
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
})
}
}
}
请注意,我已在Interface Builder中的所需视图上添加了UIRotationGestureRecognizer
,这就是该函数为@IBAction
的原因.
Note that I added the UIRotationGestureRecognizer
on the desired view from the Interface Builder, that's why the function is an @IBAction
.
输出:
这篇关于Swift-旋转手势,旋转增量为90度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!