Mike Schmidt
Mike Schmidt

Reputation: 1065

Swift Bar Button Item 360 Spin?

I have seen similar questions on here before, but they relate to just simple buttons, not bar button items. Keep in mind- bar button items and regular buttons have different properties, thus the answers on the other posts will not work in this situation.

Is there a way, in swift, that I can make my refresh bar button item spin 360 degrees one time (to show that an action occurred)?

Upvotes: 0

Views: 1271

Answers (1)

ZGski
ZGski

Reputation: 2538

In order to animate a UIBarButtonItem, we need to assign it a customView and animate that instead.

What I've done below is create an ordinary UIButton, and I've assigned it's image to a refresh icon named "refresh". Next, I set my UIBarButtonItem's customView to be my new button. Now that barButton has a customView, I can call my rotateBarButton() method to perform the animation code.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var barButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(frame: CGRectMake(0, 0, 40, 40)) // Create new button & set its frame
        button.setImage(UIImage(named: "refresh"), forState: .Normal) // Assign an image 
        barButton.customView = button // Set as barButton's customView
    }

    func rotateBarButton() {
        // Gets you half way there //
        UIView.animateWithDuration(0.05, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.barButton.customView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
            }, completion: nil)
        // Rotates all the way around //
        UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions.CurveEaseIn, animations: {
            self.barButton.customView?.transform = CGAffineTransformMakeRotation(CGFloat(M_PI * 2))
            }, completion: nil)
    }
}

Upvotes: 1

Related Questions