Rotate view by dragging
<p>I have been trying to implement an animation of sorts where a view rotates about a point when the user drags across the screen. I have implemented the part of it that controls the rotating (the part pertaining to this question). You can view all the code I have <a href="http://pastebin.com/tkNM6MfC" rel="nofollow noreferrer">here</a> if you would like to (it's short). </p>

<p>The code that controls the rotation is mainly in <code>touchesBegan</code> and <code>touchesMoved</code>:</p>

<pre><code>var p = CGPoint.zero
// ...
override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
    p = (touches.first?.location(in: self))!
}

override func touchesMoved(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
    let dev = p.x - (touches.first?.location(in: self).x)!
    let angle = 2 * CGFloat(M_PI) - atan(dev / p.y)
    self.transform = CGAffineTransform(rotationAngle: angle)
}
</code></pre>

<p>Now here is the problem: when my finger drags below the initial middle of the view (the middle before any rotation), it works perfectly fine; however, when my finger drags above the initial middle of the view, the view is rotated to the wrong amount, and it jumps back and forth between two positions really fast, so it looks like there is a copy of the view.</p>

<p>I don't know if it is not working because of my general math/logic or with my implementation. </p>

<p>Why does it not work correctly when I drag above the initial middle of the view, and how can I fix it?</p>