How to change the state of an UIButton in iOS using Swift? - ios

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;

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

// 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)
}
}

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

//Method 1
//Create IBAction and check button selected or not...There is no need to set //sender.selected to true or false in the if/else statement.
#IBAction func rememberMe(sender: UIButton) {
sender.selected = !sender.selected
if sender.selected {
self.setImage(UIImage(named: "RememberMe_Checkmark"), forState: .Normal)
} else {
self.setImage(UIImage(named: "No_Checkmark"), forState: .Normal)
}
}
//METHOD 2 With Custom Type from Storyboard
enter image description here
Click on the Image Link to See Sample
From the Storyboard do the following
1) Change the Button type to "Custom"
2) Change the State Config to "Selected"
3) Set the Image to the Checkbox Icon with a checkmark asset
4) Set the Background to the Checkbox Icon without a checkmark asset
//Create and IBAction from the Button and enter this single Line of Code
#IBAction func rememberMe(sender: UIButton) {
sender.selected = !sender.selected
}

Related

Toggle between select/deselect UIButton

I have a button which I want to change background color and text when tapped(select) and bring it back to its original state when tapped again (deselect). I am able to select it but I am not being able to deselect it. I have researched on SO and I am getting errors in this code in the if-else part
#IBAction func btn1Pressed(_ sender: AnyObject) {
sender.setTitleColor(UIColor.blue, for: UIControlState.normal)
(sender as! UIButton).backgroundColor = UIColor.green
if sender.isSelected {
sender.selected = false
}
else {
sender.selected = true
}
}
Try this:
#IBAction func btnPressed(_ sender: AnyObject) {
guard let button = sender as? UIButton else { return }
if !button.isSelected {
button.isSelected = true
button.setTitleColor(UIColor.blue, for: UIControl.State.normal)
button.backgroundColor = UIColor.green
}
else {
button.isSelected = false
button.setTitleColor(UIColor.green, for: UIControl.State.normal)
button.backgroundColor = UIColor.blue
}
}
It sounds to me like UISwitch is what you're looking for. Give it a try instead of wasting time implementing something that's already there for you.
try this
#IBAction func btn1Pressed(sender: UIButton) {
if sender.selected {
sender.selected = false
sender.setTitleColor(UIColor.redColor(), forState: .Normal)
sender.backgroundColor = UIColor.blackColor()
}
else {
sender.selected = true
sender.setTitleColor(UIColor.redColor(), forState: .Selected)
sender.backgroundColor = UIColor.blackColor()
}
}
Change background color of selected button from storyboard like below in state config choose selected and then change background color and also coustomize default for normal button.
and use below in action
(sender as! UIButton).selected = !(sender as! UIButton).selected
Please try this code first you need to crate action and propert of the button like
#IBOutlet var btn_ButtonPressed: UIButton!
then Action.
#IBAction func click_ButtonPressed(_ sender: Any) {
if !sender.isSelected() {
sender.selected = true
btn_ButtonPressed.setTitleColor(UIColor.red, forState: .normal)
btn_ButtonPressed.backgroundColor = UIColor.yellow
}
else {
sender.selected = false
btn_ButtonPressed.setTitleColor(UIColor.yellow, forState: .normal)
btn_ButtonPressed.backgroundColor = UIColor.red
}
}
this one worked fine for me!
//
#IBAction func buttonColorChanger(sender : UIButton ) {
if button.isSelected == false
{
button.backgroundColor = UIColor.purple
print("selected")
button.setTitle("selected", for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.isSelected = true
}else{
button.backgroundColor = UIColor.white
print("unselected")
button.isSelected = false
}
}
A cleaner approach would be:
#objc private func buttonTapped(_ sender: UIButton) {
sender.isSelected.toggle()
if selected {
// Setup appearance for selected state.
} else {
// Setup appearance for deselected state.
}
}

Removed Selected State on Button While Clicking a Different Button (Swift)

I'm trying to figure out the logic in toggling button states in Swift. The concept is very simple:
I have three buttons on the screen.
When I click one button, it toggles to a 'selected' state
When I click a different button, I want it to toggle the currently selected button to a 'non-selected' state and toggle the new button to 'selected'
I have this function I use on TouchUpInside for the buttons on the screen but at the moment it's possible to have them all 'selected' which I don't want:
func highlightTrack(sender:UIButton){
if(!sender.selected){
sender.selected = true
sender.backgroundColor = UIColor.blueColor()
} else {
sender.selected = false
}
}
I come from the world of Javascript so I may just have my logic crossed up but is there a way to detect currently selected buttons on the screen and turn them off or is this closer to a 'radio' button type logic?
My issue is that these buttons are created programmatically depending on certain conditions so technically I'm not supposed to be created IBOutlets on the fly like that correct (IB meaning 'Interface Builder'?)?
Thanks for your help!
func highlightTrack(sender:UIButton) {
if sender.isSelected {
return
}
btn1.isSelected = false
btn2.isSelected = false
sender.isSelected = true
}
Connect following action function with all your three buttons using TouchUpInside control event.
button1.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button3.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
#IBAction func highlightTrack(button: UIButton) {
if button.isSelected {
return
}
button1.isSelected = false
button1.backgroundColor = UIColor.white
button2.isSelected = false
button2.backgroundColor = UIColor.white
button3.isSelected = false
button3.backgroundColor = UIColor.white
button.isSelected = true
button.backgroundColor = UIColor.blue
}
Another solution:
#IBAction func highlightTrack(button: UIButton) {
if button.isSelected {
return
}
updateButtionSelectionState(button: button, isSelected: (button == button1))
updateButtionSelectionState(button: button, isSelected: (button == button2))
updateButtionSelectionState(button: button, isSelected: (button == button3))
}
func updateButtionSelectionState(button: UIButton, isSelected: Bool) {
button.isSelected = isSelected
button.backgroundColor = isSelected ? UIColor.blue : UIColor.white
}

UIButton text returns to original value after setting a new value to it

My UIButton is in a UICollectionviewcell, which is in a UICollectionview, which is in a UITableViewCell, which is in a UITableView.
The button is a like button, I want it to change its text when clicked. But after changing the text, it returns the original value. What might be the reason here?
Here is what it looks like:
https://gfycat.com/UnlawfulGroundedErin
This is the onClickEvent of button:
#IBAction func actionClick(sender: MyActionButton) {
if (sender.toggle){
print("Do dislike call here.")
sender.toggle = false
sender.titleLabel?.text = "Like"
}else{
print("Do like call here.")
sender.toggle = true
sender.titleLabel?.text = "Unlike"
}
}
Try This. It will work properly
#IBAction func actionClick(sender: MyActionButton) {
if (sender.toggle){
print("Do dislike call here.")
sender.toggle = false
sender.titleLabel?.text = "Like"
sender.setTitle("Like", forState: UIControlState.Normal)
}else{
print("Do like call here.")
sender.toggle = true
sender.setTitle("Unlike", forState: UIControlState.Normal)
}
}
UIButton have different texts for its title in different states.
Just for your knowledge
In viewDidLoad:
btnObject.setTitle("Like", forState: UIControlState.Normal)
btnObject.setTitle("Unlike", forState: UIControlState.Selected)
then in method actionClick: if you write only one statement,
sender.selected = !sender.selected;
it will work.
try this
#IBAction func actionClick(sender: UIButton) {
if sender.isSelected() {
sender.selected = false
sender.setTitle("Like", forState: UIControlState.Normal)
}
else {
sender.selected = true
sender.setTitle("Unlike", forState: UIControlState.Normal)
}
}
Choice-2
var isSelectFirst:Bool = false
#IBAction func actionClick(sender: UIButton) {
if isHighLighted == false{
sender.setTitle("Unlike", forState: UIControlState.Normal)
isHighLighted = true
}else{
sender.setTitle("Like", forState: UIControlState.Normal)
isHighLighted = false
}
}

Select/deselect buttons swift xcode 7

Part way done with learning swift but I hit a small wall and yet again, I'm sure I'm just a bit new at this and an easy solution is there but I'm having trouble figuring out how to select/deselect buttons below is what I have so far and it is a button turns into a checkmark when clicked on... I've gotten that far but I need that button to deselect when clicked on again and then obviously be able to be clicked again if need be.
#IBAction func buttonPressed(sender: AnyObject) {
sender.setImage(UIImage(named: "Checkmark.png"), forState: .Normal)
}
Swift 3 note: .selected and .checked are now lower case UIControlState values in the SDK, and some of the methods have been renamed:
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
You can also now use image literals with Xcode 8 instead of UIImage(named:):
#imageLiteral(resourceName: "Unchecked")
Swift 2:
Why not use the .Selected state of the button as the "checked" state, and the .Normal state as the "unchecked" state.
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
// ...
#IBAction func buttonPressed(sender: AnyObject) {
if let button = sender as? UIButton {
if button.selected {
// set deselected
button.selected = false
} else {
// set selected
button.selected = true
}
}
}
You dont need to set selected in condition. I just doing with following method in swift:
func selectDeselect(sender: UIButton){
sender.selected = !sender.selected
if(sender.selected == true)
{
sender.setImage(UIImage(named:"select_heart"), forState: UIControlState.Normal)
}
else
{
sender.setImage(UIImage(named:"heart"), forState: UIControlState.Normal)
}
}
Here is Working code for swift 4.
Make Sure you need to connect Button IBAction Outlet as UIButton and set default button image from storyboard whatever you want.
#IBAction func btnTapped(_ sender: UIButton) {
if sender.currentImage == UIImage(named: "radio_unchecked"){
sender.setImage(UIImage(named: "radio_checked"), for: .normal)
}else{
sender.setImage(UIImage(named: "radio_unchecked"), for: .normal)
}
}
update for Swift 4+ :
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), forState: .Normal)
button.setImage(UIImage(named: "Checked"), forState: .Selected)
#IBAction func buttonPressed(sender: AnyObject) {
if let button = sender {
if button.isSelected {
// set deselected
button.isSelected = false
} else {
// set selected
button.isSelected = true
}
}
}
Set uncheck image on default state from storyboard and check image on selected state from storyboard.
#IBAction func buttonPressed(sender: AnyObject) {
buttonOutlet.isSelected = !buttonOutlet.isSelected
}
private(set) lazy var myButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "Unchecked"), for: .normal)
button.setImage(UIImage(named: "Checked"), for: .selected)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
#objc
func buttonTapped(sender: AnyObject) {
sender.isSelected.toggle()
}
To select only the pressed button out of three buttons and deselect the others when designated button is pressed.
#IBAction func buttonPressed(_ sender: UIButton) {
// Deselect all buttons
button1.isSelected = false
button2.isSelected = false
button3.isSelected = false
// Select the pressed button
sender.isSelected = true
}

Multiple UIButtons only one can be selected - subclass in swift

I have written a subclass that selects and deselects buttons. I have put this subclass on around 5 buttons in a View Controller.
I want to amend the code so that if the user selects one and then selects another the first one gets deselected.
I was thinking of using the .tag on the button to count which buttons has been selected and remove the selection when the next button is pressed.
Here is the code :
thanks
class ChangeColour: UIButton {
var buttontagpressed: Int = 0
var isChecked:Bool = false{
didSet{
if isChecked == true {
self.backgroundColor = UIColor(red:0.27, green:0.29, blue:0.31, alpha:1.0)
self.setTitleColor(UIColor.whiteColor(), forState: .Normal)
buttontagpressed = self.tag
}
else
{
self.backgroundColor = UIColor(red:0.09, green:0.83, blue:0.56, alpha:1.0)
self.setTitleColor(UIColor(red:0.24, green:0.24, blue:0.24, alpha:1.0), forState: .Normal)
}
}
}
override func awakeFromNib() {
self.addTarget(self, action: "buttonselected:", forControlEvents: UIControlEvents.TouchUpInside)
self.isChecked = false
}
func buttonselected (sender:UIButton) {
buttontagpressed = self.tag
if (sender == self)
{
if isChecked == true
{
isChecked = false
}
else
{
isChecked = true
}
}
}
}
Rather than using tag (which I think is quite an ugly solution) I would be inclined to add a property to your class which keeps a reference of the previously selected button. This solution would be much more elegant - Or you could use UINotificationCenter to broadcast a message to all buttons to initiate the deselect.

Resources