Search code examples
iosswiftimagebuttonuibarbuttonitem

Change UIBarButtonItem Icon after pressed iOS swift


In the viewDidload method, I've declared a button and set RightBarButton...

    let btnFavourite = UIButton(frame: CGRectMake(0,0,30,30))
    btnFavourite.addTarget(self, action: "btnFavourite:", forControlEvents: .TouchUpInside)
    btnFavourite.setImage(UIImage(named: "star"), forState: .Normal)
    btnFavourite.setImage(UIImage(named: "star_filled"), forState: .Highlighted)
    let rightButton = UIBarButtonItem(customView: btnFavourite)
    self.navigationItem.setRightBarButtonItems([rightButton], animated: true)

How do I pressed the button from image 'star.png' then change to 'star_filled.png'? and press the button from 'star_filled.png' to 'star.png'?

How to make two functions like

func btnFavourite()
{
    //clicked the favourite button then image change to star_filled.png
}

fun btnUnfavourite()
{
    //clicked the button then the bar button image change to star.png
}

Solution

  • Create Method which will update you Button based on the state of self.isFavourited

    var isFavourited = false;//declare this above the viewDidload()
    
    func updateRighBarButton(isFavourite : Bool){
        let btnFavourite = UIButton(frame: CGRectMake(0,0,30,30))
        btnFavourite.addTarget(self, action: "btnFavouriteDidTap", forControlEvents: .TouchUpInside)
    
    
        if isFavourite {
             btnFavourite.setImage(UIImage(named: "star_filled"), forState: .Normal)
        }else{
            btnFavourite.setImage(UIImage(named: "star"), forState: .Normal)
        }
        let rightButton = UIBarButtonItem(customView: btnFavourite)
        self.navigationItem.setRightBarButtonItems([rightButton], animated: true)
    }
    
    
    
    func btnFavouriteDidTap()
    {
        //do your stuff
        self.isFavourited = !self.isFavourited;
        if self.isFavourited {
            self.favourite();
        }else{
            self.unfavourite();
        }
        self.updateRighBarButton(self.isFavourited);
    }
    
    
    func favourite()
    {
        //do your favourite stuff/logic
    }
    
    func unfavourite(){
        //do your unfavourite logic
    }
    

    In the viewDidload method, call first time, i.e.

    self.updateRighBarButton(self.isFavourited);//first time self.isFavourited will be false