UIButton color issues
10,064
Solution 1
Try setting the individual events, such as:
[b1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
Solution 2
The reason your original code wasn't working is because you were passing in a UIControlEvents
parameter instead of a UIControlState
parameter.
[b1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
That will set the color for the normal state, and, unless you set colors for other states, it will persist across all states. To change the color for the other states, just call the same method with other states (UIControlStateNormal
, UIControlStateHighlighted
, UIControlStateDisabled
, UIControlStateSelected
):
[b1 setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
Author by
CodeGuy
Updated on June 04, 2022Comments
-
CodeGuy almost 2 years
How can I change the color of the text on my UIButton. Here is my current code:
UIButton *b1 = [[UIButton alloc] init]; b1.frame = CGRectMake(280,395,30,30); [[b1 layer] setCornerRadius:8.0f]; [[b1 layer] setMasksToBounds:YES]; [[b1 layer] setBorderWidth:1.0f]; [[b1 layer] setBackgroundColor:[botCol CGColor]]; b1.titleLabel.font = [UIFont boldSystemFontOfSize:24]; [b1 setTitleColor:[UIColor redColor] forState:UIControlEventAllEvents]; [b1 addTarget:self action:@selector(NextButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; [b1 setTitle:@">" forState:UIControlStateNormal]; [self.view addSubview:b1];
Here is what it looks like (ignore the background color and stuff):
Now, how can I get the arrow to be red? As you see above, I already have the following:
[b1 setTitleColor:[UIColor redColor] forState:UIControlEventAllEvents];
but it isn't working.
-
CodeGuy about 13 yearsnow what if I wanted the background to be white when a user touched the button? what would the code look like?
-
sudo rm -rf about 13 years@reising: I don't think you can trigger that with an event. The only workaround I can think of is to add this into the action that's fired in your code (NextButtonPressed).
[[b1 layer] setBackgroundColor:[UIColor greenColor].CGColor];
However, you'd have to makeb1
an instance variable to access it outside of the original method.