Question

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.

Was it helpful?

Solution

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];

OTHER TIPS

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.

Have you tried this

[cancelButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[cancelButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];

This will solve your problem,

    [cancelButton setTitleColor:YOUR COLOR forState:SPECIFIED STATE];

The state values are :

UIControlStateNormal
UIControlStateHighlighted                
UIControlStateDisabled    
UIControlStateSelected 

Try using

- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state

for specifying colors for all the required states.

Swift:

let button = UIButton (type: UIButtonType.system)

This will create a button that uses the standard tint color just like a button added to a storyboard in interface builder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top