Ran into a minor problem today when I was attempting to manually create a UIButton in my iPhone app. I attempted to create/configure the button through code similar to the following:
CGRect frame = CGRectMake(0, 0, 200, 52);
UIButton b = [[UIButton alloc] initWithFrame:frame];
b.titleLabel.text = @"My Button";
b.titleLabel.textColor = [UIColor whiteColor];
b.backgroundColor = [UIColor clearColor];
The key mistake is highlighted in red. I attempted to manually set the text an color of the UIButton‘s label, when in fact the UIButton would automatically reconfigure the label (including it’s text) in response to state changes.
The correct approach is to use send the setXXX:forState: messages to the UIButton object itself. For example, the following code sets the text/color for the UIControlStateNormal state.
[b setTitle:@"Test" forState:UIControlStateNormal];
[b setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
Hello Ryan,
Thanks for this tip, great help
Thanks, saved me some time!
Awesome, saved me a headache!
Thanks.Saved my precious time.
for your help. Spared me some digging.
Thanks dude
I tried doing this, but the button text doesn’t update still
I want to try to change the text value from “start” to “stop” toggle when someone presses it like the stop watch application that came w/ the iphone.
Any hint on why that is the case?
The possible control states are:
UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
UIControlStateApplication
UIControlStateReserved
These are the possible values that you could have a different appearance for. For what you’re talking about, you would need to track the state yourself (running versus stopped) and change the characteristics of the UIControlStateNormal.
Nicely done. Thank you!
thanks a lot dear .
There is a great Tutorial about this for the german dev community…
https://bedifferently.wordpress.com/2011/11/17/uibutton-bearbeite-den-titel-teil-2/
hope it helps…