iOS: How to achieve the same highlight that a UIButton background image has?

103 Views Asked by At

I am trying to achieve the same highlight that a UIButton background image has, but for a UIButton with no background image. This is what it looks like when the UIButton with an image background has been highlighted.

enter image description here

However, I am unsuccessful achieving this when using a non background image button. This is the code I have so far for my custom button.

- (void)setHighlighted:(BOOL)highlighted
{
    if (highlighted) {
        self.backgroundColor =  [self.backgroundColor colorWithAlphaComponent:0.9f];
        self.titleLabel.alpha = 0.9f;
    } else {
        self.backgroundColor =  [self.backgroundColor colorWithAlphaComponent:1.0f];
        self.titleLabel.alpha = 1.0f;
    }

    [super setHighlighted:highlighted];
}

The main problem is it isn't dark enough. Is there a way I can change the background color and label color to resemble a UIButton with an image background that has been highlighted?

Edit: I know alpha makes it lighter, but this was recommend in a thread when I was researching.

Edit: I created this method

  - (void)setHighlighted:(BOOL)highlighted
{
    if (highlighted) {
        if (!overlayView) {
            overlayView = [[UIView alloc] initWithFrame:self.bounds];
            overlayView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        }

        [self addSubview:overlayView];
    } else {
        [overlayView removeFromSuperview];
    }
    [super setHighlighted:highlighted];
}

This seems to work well, but not sure if there is a better alternative.

0

There are 0 best solutions below