I need to make an icon rotate depending on the current rotation of another UIImageview. For that I have one UIImageView which movement is controlled by a rotation user gesture. I also have an UIView which contains icons that I need to rotate properly. This UIView have always the exact same position and rotation as the UIImageview.
Graphically this is what I need to do:
I manage the motion with this code:
I managed the gesture with the following code:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
origin = (touches.first?.locationInView(self.view))!
xOffSet = CGVector(dx:(origin.x)-rotateImageView.center.x, dy:(origin.y) - rotateImageView.center.y)
startingAngle = atan2(xOffSet.dy,xOffSet.dx)
//save the current transform
tempTransform = rotateImageView.transform
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first
if touch!.view === rotateImageView || touch!.view === viewIcons {
let touchPoint = touches.first?.locationInView(self.view)
yOffSet = CGVector(dx:touchPoint!.x - rotateImageView.center.x, dy:touchPoint!.y - rotateImageView.center.y)
let angle = atan2(yOffSet.dy,yOffSet.dx)
let deltaAngle = angle - startingAngle!
rotateImageView.transform = CGAffineTransformRotate(tempTransform, deltaAngle)
viewIcons.transform = CGAffineTransformRotate(tempTransform, deltaAngle)
rotateIconsWithImageView (ivClock , angle: deltaAngle)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
startingAngle = nil
}
//reset in case drag is cancelled
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
rotateImageView.transform = tempTransform
startingAngle = nil
}
This code prevents another problem which happens when the user starts the gesture on another section of the screen. Detailed information can be seen on this another stackoverflow thread: Rotation gesture produces undesired rotation
For the rotation if the icon I use this function which I invoke as the last instruction on touchesMoved:
func rotateIconsWithImageView (imageview:UIImageView , angle: CGFloat ) {
imageview.transform = CGAffineTransformRotate(tempTransform, -angle)
}
This works fine normally (as you see on the gif) if I start the gesture without changing the touch area. But If the user changes the touch area the rotation is wrong and since I'm not used with transform I'm not sure what exactly to do.
This gif illustrate the issue:
Thanks in advance