luke luke - 3 months ago 18
Swift Question

rotate png inside uibutton

I have a

UIButton
inside the
titleView
of the nav bar. I have a downwards caret image that I want to rotate 180 degrees everytime the user taps the button. How can I do this?

enter image description here

Answer Source

Here's an example of how can you do it using Transforms:- The code works with all the elements that inherits from UIView

UIView.animate(withDuration: 0.5) {
            self.yourButton.imageView?.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) / 180.0)

}

To set it back to original position:-

UIView.animate(withDuration: 0.5) {
      self.yourButton.imageView?.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) * 180.0)

}