Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep UIButton Selected/Highlighted after touch

I'd like my button to remain highlighted after the user taps it. If the user taps the button again I'd like it to become de-selected/unhighlighted. I'm not sure how to go about doing this in swift. I'm currently setting the button highlight image and selected image to the same .png using interface builder.

When I run the app and tap the button, it changes to my highlight image for as long as my finger remains on the button.

like image 872
dcbenji Avatar asked Jul 19 '14 20:07

dcbenji


2 Answers

Use below code declare isHighLighted as instance variable

//write this in your class
 var isHighLighted:Bool = false


override func viewDidLoad() {

    let button  = UIButton(type: .system)

    button.setTitle("Your title", forState: UIControlState.Normal)
    button.frame = CGRectMake(0, 0, 100, 44)

    self.view.addSubview(button as UIView)

    button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

}

func buttonClicked(sender:UIButton)
{
    dispatch_async(dispatch_get_main_queue(), {

        if isHighLighted == false{
            sender.highlighted = true;
            isHighLighted = true
        }else{
            sender.highlighted = false;
            isHighLighted = false
        }
     });
}

I would recomend to use selected state instead of highlighted the below code demonstarate with selected state

override func viewDidLoad() {

    let button  = UIButton(type: .system)

    button.setTitle("Your title", forState: UIControlState.Normal)
    button.frame = CGRectMake(0, 0, 100, 44)

    self.view.addSubview(button as UIView)
    //set normal image 
    button.setImage(normalImage, forState: UIControlState.Normal)
    //set highlighted image 
    button.setImage(selectedImage, forState: UIControlState.Selected)

    button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

}

func buttonClicked(sender:UIButton)
{
      sender.selected = !sender.selected;
}
like image 86
codester Avatar answered Oct 05 '22 06:10

codester


func buttonPressed(_ sender: UIButton) {

    // "button" is a property

    if button.isSelected {
        button.setImage(UIImage(named: "filled-heart"), for: .normal)
        button.isSelected = false
    }else {
        button.setImage(UIImage(named: "empty-heart"), for: .selected)
        button.isSelected = true
    }
}
like image 25
nenad Avatar answered Oct 05 '22 04:10

nenad