Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

objective c - 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.

question from:https://stackoverflow.com/questions/11583387/uibutton-title-changes-to-default

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...