acreek
acreek

Reputation: 325

Manually setting a UIButton state

I UIButton using + buttonWithType:

What I need to figure out is how to manually change the button state. There are times when I need it to be set to "disabled."

I read through the UIButton documentation but I cannot seem to find anything about manually setting a button state.

Any thoughts would be greatly appreciated.

Upvotes: 20

Views: 49338

Answers (7)

andrewlundy_
andrewlundy_

Reputation: 1153

To accommodate the needs of setting a different button look when it's selected, set isSelected = true.

Here is an example of setting the state, and changing the UIButton appearance based on that state, using a quiz game environment:

if sender.titleLabel?.text == correctAnswer {
    sender.isSelected = true
    // Set title color and image based on 'selected' state.
    sender.setTitleColor(.systemBlue, for: .selected)
    sender.setImage(Utilities.sharedInstance.returnAnswerButtonImage(for: .correctlyAnswered).withRenderingMode(.alwaysOriginal), for: .selected)
    sender.backgroundColor = .white
    sender.tintColor = .systemBlue
    // moveToNextQuestion()
} else {
    sender.isSelected = true
    sender.setTitleColor(.systemBlue, for: .selected)
    sender.setImage(Utilities.sharedInstance.returnAnswerButtonImage(for: .incorrectlyAnswered).withRenderingMode(.alwaysOriginal), for: .selected)
    sender.backgroundColor = .red
    sender.tintColor = .systemBlue
}

Upvotes: 0

Zouhair Sassi
Zouhair Sassi

Reputation: 1411

Objective C:

button.selected = Yes;
button.highlighted = NO;
button.enabled = Yes;

Swift 4:

button.isSelected = true 
button.isEnabled = true

Also you can use:(swift 4)

 if (button.state == .selected) {
   //do something
 }

Upvotes: 4

Ben Gottlieb
Ben Gottlieb

Reputation: 85542

Did you try button.enabled = NO;?

Swift 5.0

button.isEnabled = false

Upvotes: 49

Firas Shrourou
Firas Shrourou

Reputation: 715

for Swift 3 you can use

button.isSelected = true

Upvotes: 2

Lorne K
Lorne K

Reputation: 109

For anyone arriving here looking to change the 'state' of the button (as opposed to 'enabled'). Stephen is correct "This attribute is read only—there is no corresponding setter method."

What you really want to set is the state of the buttons cell.

[[myNSButtonOutlet cell] setState: NSOnState];  //Options NSOnState, NSOffState, NSMixedState

Upvotes: 0

Birju
Birju

Reputation: 1130

You can manually set state of UIButton.

UIButton *btnCheck=[UIButton buttonWithType:UIButtonTypeCustom];

if(btncheck isselected])
{
    btncheck.selected=FALSE;
}
else
{
    btncheck.selected=TRUE;
}

You can do operation on UIButton as per your requirement like perform some action when UIButton is selected and while not selected.

Hope this will help you....

Upvotes: 3

roberthuttinger
roberthuttinger

Reputation: 1194

there are also the states:

   button.highlighted = NO;
   button.selected = NO;

Upvotes: 28

Related Questions