2

I have a UIButton subclass that does not use a UIImage background, just a background color. One thing i've noticed is that when you set a button's background image, there is a default highlighted state where the button would turn slightly darker when pressed.

Here is my current code.

 - (void)awakeFromNib
{
    [super awakeFromNib];
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 4;
    [self.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [self setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
}

With this code,I am not given that default selection state if i only set the background color. I've tried overriding this with - (void)setHighlighted:(BOOL)highlightedand setting the darker color of the button, but either I am not getting the color right or theres more to just setting the color.

I'm unsure of how i can mimic that selection state. Any help would be appreciated!

3254523
  • 3,016
  • 7
  • 29
  • 43
  • 1
    Try: http://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted – Yarneo May 15 '14 at 18:43

2 Answers2

0
[self setTitleColor:[UIColor whiteColor] UIControlStateHighlighted]; // To set title label color for highlighted state.
mithlesh jha
  • 343
  • 2
  • 11
0

You can do this by registering events to the button.

[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown | UIControlEventTouchDragInside];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchCancel | UIControlEventTouchDragExit];

After you do that, you need to implement both buttonTouchDown: and buttonTouchUp:.

    - (void) buttonTouchDown:(UIButton *)sender {
        // button color when it's highlighted
        sender.backgroundColor = [UIColor red];
    }
jhk
  • 261
  • 3
  • 13