Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate UIBarButtonItem Swift

In Swift, I have a hamburger bar button, so when tapped I want that hamburger Bar button to rotate 90 degrees (so that the lines are vertical) and then when you click it again I would like it to go back to it's original state (horizontal)

NOTE: Can you make sure that this works for a UIBarButtonItem, because some solution to a normal UIButton does not work.

like image 966
C.Elam Avatar asked Dec 23 '22 16:12

C.Elam


2 Answers

I use a UIButton inside of UIBarButtonItem to achieve this, and a variable with state vertical or not

this is my storyboard setup enter image description here

Here is the code of simple view controller

import UIKit

class ViewController: UIViewController {

    var isVertical : Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func rotateAction(_ sender: Any) {
        if(!self.isVertical)
        {
            UIView.animate(withDuration: 0.2, animations: { 
                self.navigationItem.leftBarButtonItem?.customView?.transform =  CGAffineTransform(rotationAngle: 90 * .pi / 180)
            }, completion: { (finished) in
                self.isVertical = true
            })
        }else{
            UIView.animate(withDuration: 0.2, animations: {
                self.navigationItem.leftBarButtonItem?.customView?.transform =  CGAffineTransform.identity
            }, completion: { (finished) in
                self.isVertical = false
            })
        }

    }


}

Result

enter image description here

Hope this helps

like image 178
Reinier Melian Avatar answered Jan 04 '23 17:01

Reinier Melian


@IBAction func rotateAction1(_ sender: Any) {
    if (!self.isVertical) {

        UIView.animate(withDuration: 0.2, animations: {
            self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: 90 * .pi / 180)
        }, completion: {
            (finished) in
            self.isVertical = true

        })

        revealViewController().revealToggle(true)
    } else {
        UIView.animate(withDuration: 0.2, animations: {
            self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform.identity
        }, completion: {
            (finished) in
            self.isVertical = false
        })
        revealViewController().revealToggle(false)
    }
}
like image 28
C.Elam Avatar answered Jan 04 '23 16:01

C.Elam