I created a UIGestureRecognizer to rotate a view with only one finger.
The view rotate at the beginning but as soon as it reached a certain degree the rotation rotate in the other direction.
Can you help me with my code?
UIViewcontroller <- Everything is fine here
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let wheel = TestWheelView()
wheel.frame = CGRect.init(x: self.view.center.x - 120, y: self.view.center.y - 120, width: 240, height: 240)
self.view.addSubview(wheel)
wheel.addGestureRecognizer(TestRotateGestureRecognizer())
}
UIGestureRecognizer <- The problem is here
import UIKit
class TestRotateGestureRecognizer: UIGestureRecognizer {
var previousPoint = CGPoint()
var currentPoint = CGPoint()
var startAngle = CGFloat()
var currentAngle = CGFloat()
var currentRotation = CGFloat()
var totalRotation = CGFloat()
func angleForPoint(_ point:CGPoint) -> CGFloat{
var angle = atan2(point.y - (self.view?.center.y)!, point.x - (self.view?.center.x)!)
return angle
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if let firstTouch = touches.first {
previousPoint = firstTouch.previousLocation(in: self.view)
currentPoint = firstTouch.location(in: self.view)
startAngle = angleForPoint(previousPoint)
currentAngle = angleForPoint(currentPoint)
currentRotation = currentAngle - startAngle
totalRotation += currentRotation
self.view?.transform = CGAffineTransform(rotationAngle: totalRotation)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
}
}