I used the information from How to rotate an UIImageView using TouchesMoved in my own project. But I found a problem, and I can’t figure out how to solve it.
The view in the original post has the same problem but with the small view it is almost not noticeable. A made this example code. See how the view “jumps”. The touch point is always left of the anchor point. How can I avoid this jump.
class ViewController: UIViewController {
var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
myView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 200))
myView.center = self.view.center
myView.isUserInteractionEnabled = true
myView.backgroundColor = UIColor.red
self.view.addSubview(myView)
myView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch = touches.first!
if touch.view === myView {
let position = touch.location(in: self.view)
let target = myView.center
let angle = atan2(target.y-position.y, target.x-position.x)
myView.transform = CGAffineTransform(rotationAngle: angle)
}
}
}