3

Here's my code. It creates a white button that turns purple on being pressed. What I want is a purple button.

    if (!backButton) {
    backButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [backButton setTitle:@"Back" forState:UIControlStateNormal];
    backButton.titleLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
    CGSize size = [aboutButton.titleLabel.text sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:23]];
    backButton.frame = CGRectMake(screenWidth/2 - size.width/2, screenHeight-size.height*4, size.width, size.height);
    backButton.tintColor = [UIColor colorWithRed:123/255.0 green:47/255.0 blue:85/255.0 alpha:1]; //This is the color I want the button to be in its normal state.
    [backButton addTarget:self action:NSSelectorFromString(@"displaySettingsScreen") forControlEvents:UIControlEventTouchUpInside];
}
[self.view addSubview:backButton];

What am I missing?

Joel Derfner
  • 2,207
  • 6
  • 33
  • 45

2 Answers2

2

Sadly, the tintColor property doesn't work for RoundedRect button types.

See here: Why is my UIButton.tintColor not working?

To get around this, I use a single-segment UISementedControl, in place of the UIButton I wanted colored.

This answer here describes the technique: https://stackoverflow.com/a/4971371/785411

Another alternative would be to use a purple image for the button - though that would require a bit more work.

Community
  • 1
  • 1
Chris McGrath
  • 1,936
  • 16
  • 17
1

Rounded rect buttons are hard to change, so use a custom button instead, and set the background color:

if (!backButton) {
        backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setTitle:@"Back" forState:UIControlStateNormal];
        backButton.titleLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
        CGSize size = [aboutButton.titleLabel.text sizeWithFont:[UIFont fontWithName:@"Helvetica Neue" size:23]];
        backButton.frame = CGRectMake(screenWidth/2 - size.width/2, screenHeight-size.height*4, size.width, size.height);
        backButton.layer.cornerRadius = 6.0f;
        backButton.backgroundColor = [UIColor colorWithRed:123/255.0 green:47/255.0 blue:85/255.0 alpha:1]; //This is the color I want the button to be in its normal state.
        [backButton addTarget:self action:NSSelectorFromString(@"displaySettingsScreen") forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:backButton];

You'll need to add the QuartzCore framework, and import it (for the layer properties to work).

rdelmar
  • 103,982
  • 12
  • 207
  • 218