I have a segmented control and I'd like to animate a UIView to rotate clockwise when the right side of the control is tapped, and counter-clockwise when the left side is tapped. My code to rotate is:
func rotateRight() {
UIView.animate(withDuration: 0.5, animations: {
self.profileImageView.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) / 180.0)
self.profileImageView.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(M_PI)) / 360.0)
})
And then I'm using this code to handle the changes depending on which segment is tapped (Edited for update):
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
self.loginRegisterButton.backgroundColor = UIColor.blue
loginRegisterSegmentedControl.tintColor = UIColor.blue
rotateLeft()
// Roll to the left
} else {
self.loginRegisterButton.backgroundColor = UIColor.red
loginRegisterSegmentedControl.tintColor = UIColor.red
rotateRight()
// Roll to the right
}
So basically in the if conditional I want to call a rotateLeft()
function - how can I do this?
EDIT: Here's my full code for the animation, including Pierce's suggestion:
// Rotation
var viewAngle: CGFloat = 0 // Right-side up to start
let π = CGFloat.pi // Swift allows special characters hold alt+p to use this, it allows for cleaner code
func rotate(by angle: CGFloat) {
self.viewAngle += angle
UIView.animate(withDuration: 0.5, animations: {
self.profileImageView.transform = CGAffineTransform(rotationAngle: self.viewAngle)
self.view.layoutIfNeeded()
})
}
lazy var profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "TTTdude")
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rotate)))
imageView.isUserInteractionEnabled = true
return imageView
}()
lazy var loginRegisterSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["iOS", "Android"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.black
sc.selectedSegmentIndex = 0
sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
return sc
}()
func handleLoginRegisterChange() {
let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex)
loginRegisterButton.setTitle(title, for: .normal)
if loginRegisterSegmentedControl.selectedSegmentIndex == 0 {
self.loginRegisterButton.backgroundColor = UIColor.blue
loginRegisterSegmentedControl.tintColor = UIColor.blue
rotate(by: -2*π)
// Roll to the left
} else {
self.loginRegisterButton.backgroundColor = UIColor.red
loginRegisterSegmentedControl.tintColor = UIColor.red
rotate(by: 2*π)
// Roll to the right
}