40

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.

Dustin
  • 6,783
  • 4
  • 36
  • 53

2 Answers2

72

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).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • You're right, this was my problem. Very odd behavior, since I've done the exact same thing without any trouble before. – Dustin Jul 20 '12 at 16:35
  • It is strange how it "sometimes works!" the problem is that in the doco they mention you change the **styling** (etc) of the text using .titleLabel. What a hassle! – Fattie Dec 10 '13 at 21:42
9

The swift version of this is

startButton.setTitle("Start", forState: UIControlState.Normal)
Christopher Wade Cantley
  • 7,122
  • 5
  • 35
  • 48