How to change the state of an UIButton in iOS using Swift?
20,408
Solution 1
Check for this:
var var_button_ = UIButton()
var_button_.setBackgroundImage(UIImage(named: "button2_selected.png"), forState: UIControlState.Normal)
var_button_.selected = false
var_button_.selected = !var_button_.selected
//var_button_.selected = true
Thanks BY JNYJ
Solution 2
// You need to use the true and false for bool value in swift
buttonOutletName.selected = true buttonOutletName.selected = false
// Create IBAction and check button selected or not in swift language. You can change the button state.
@IBAction func favoriteButtonAction(sender: UIButton) {
// Save Data
sender.selected = !sender.selected;
if (sender.selected)
{
NSLog(" Not Selected");
sender.selected = false
self.setImage(UIImage(named: "checked_checkbox"), forState: .Normal)
}
else
{
NSLog(" Selected");
sender.selected = false
self.setImage(UIImage(named: "unchecked_checkbox"), forState: .Normal)
}
}
Solution 3
Create an outlet and an action for your button
Give 'button_selected' and 'button_not_selected' images for state configs Selected and Default respectively.
Then write the below code in the action,
if button.isSelected {
button.isSelected = false
}
else {
button.isSelected = true
}
I think this is the simplest way
Author by
eeschimosu
Living life like there is no tomorrow! Swift coder, pizza lover, founder and CEO at: http://superawesomestuff.co/
Updated on July 17, 2022Comments
-
eeschimosu almost 2 years
I have Objective-C working code for six buttons but I don't seem to find how to change the state of a button using Swift. So how do I make the following code work in Swift?
[self.button2 setBackgroundImage:[UIImage imageNamed:@"button2_selected.png"] forState: UIControlStateSelected]; button1.selected = NO; button2.selected = !button2.selected; button3.selected = NO; button4.selected = NO; button5.selected = NO; button6.selected = NO;