Programmatically changing UIButton font color depending on state
21,254
Solution 1
Try this code :
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
[cancelButton setFrame:CGRectMake(320 - 150, 0, 140, 40)];
[cancelButton setBackgroundColor:[UIColor clearColor]];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted]; // This will helps you during click time title color will be blue color
[cancelButton setTitle:@"Cancel" forState:UIControlStateNormal];
[cancelButton addTarget:self action:@selector(button_Action) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:cancelButton];
Solution 2
Just tried with
[cancelButton setTitleColor:[UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0/255.0 alpha:1.0] forState:UIControlStateNormal];
For more information read official documentation of UIButton
.
Solution 3
Have you tried this
[cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
Solution 4
This will solve your problem,
[cancelButton setTitleColor:YOUR COLOR forState:SPECIFIED STATE];
The state values are :
UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
Author by
Ian
Updated on July 12, 2022Comments
-
Ian almost 2 years
I'm trying to programmatically create a UIButton. However by default it's turning up white (which is the default color for my navigation bar, I feel that's relevant). I want it to just be Apple's default blue color in iOS7. I've managed to change the color for it's default state, but the moment I select it the text becomes white again. I cannot figure out how to keep it blue.
Could someone please explain to me how I can programmatically create a UIButton and have it act the same as though I created it in storyboard?
Current code:
UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom]; cancelButton.frame = CGRectMake(320 - 150, 0, 140, 40); [cancelButton setTitle:@"Cancel" forState:UIControlStateNormal]; cancelButton.titleLabel.tintColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]; cancelButton.titleLabel.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
Thank you.