Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton title changes to default

I feel like this is probably a stupid question... but anyway I have this kind of weird UIButton title behavior.

The button is set up and connected to both an action and a property in IB (the action is startButtonPushed and the property is startButton). Inside the view controller I have the action set up like this:

bool buttonStateStop;  - (IBAction)startPushed:(id)sender  {     if (buttonStateStop)      {         [appD.locationManager stopSavingLocations];         startButton.titleLabel.text = @"Start";         buttonStateStop = NO;     }     else      {         [appD.locationManager startSavingLocations];         startButton.titleLabel.text = @"Stop";         buttonStateStop = YES;             } } 

Originally I had the default title in IB set to "Start" but whenever I pressed the button it would change to "Stop" for a fraction of a second and then back. I spent a while trying to figure out why the title kept getting set back to "Start". Eventually I changed the IB title to "xxxxxx" and realized that no matter what, the IB title gets reasserted immediately after the title of the button changes.

So the question is: why does IB keep changing the button's title back to default? I've never come across this behavior before. And (obviously) how can I fix it?

Extra info: the only references to the button are the @property, @synthesize, and the statements in the code above. The view is inside of a navigation controller.

like image 619
Dustin Avatar asked Jul 20 '12 16:07

Dustin


1 Answers

You need to use setTitle:forState: method instead of setting the titleLabel.text property:

[startButton setTitle:@"Start" forState:UIControlStateNormal]; // Normal and highlighted titles do not need to be the same [startButton setTitle:@"Start!" forState:UIControlStateHighlighted]; 

What happens now is that you set the title in the label that represents the view of the current state, but once the state changes from pushed to normal, the button resets the label back to the title for the new state (which is the text that you set in the IB).

like image 141
Sergey Kalinichenko Avatar answered Sep 30 '22 20:09

Sergey Kalinichenko