Steve Maietta
Steve Maietta

Reputation: 39

UILabel text changing between two strings with each "touch up inside"

I'm learning OBJ.C/Xcode/Cocoa here and have run into a question I can't seem to find an answer for.

I want the text in a UILabel to switch between two states (ON/OFF for example) each time the user clicks the same button.

I can get the label to switch to one state, but can't get it to switch "back" when the user clicks the button again. I am assuming there is some logic required, or checking the status of the object once the button is clicked...

Does this require me to keep track of a bool or the "state" of the Label (or button)? Would this require two methods to be associated to the button, or can it happen with just one?

Thanks for any guidance/pointing in the right direction/Code snips!!!!

~Steve

I got an answer, and it works:

- (IBAction)flip:(id)sender 
{
_flipButton.selected = !_flipButton.selected;
self.flipLabel.text = (_flipButton.selected) ? @"ON" : @"OFF";
}

Upvotes: 0

Views: 334

Answers (3)

Bamsworld
Bamsworld

Reputation: 5680

- (IBAction)flip:(id)sender {
[yourButton setSelected:!yourButton.selected]; 
self.flipLabel.text = (yourButton.selected) ? @"ON" : @"OFF"; 
}

This toggles the selected state of the button then checks its state to determine which string to pass to the text property of your label.

Upvotes: 2

matthisb
matthisb

Reputation: 1118

You could call this: yourLabel.enabled = !yourLabel.enabled on button click to change the enabled-state of your UILabel. Or what kind of state do you mean ?

Upvotes: 0

miau
miau

Reputation: 227

the easiest way (I think) is to store a BOOL with the state of the UILabel and (on each click of the button) negate the BOOL and set the appropriate text of the Label

Upvotes: 1

Related Questions