Avoid UIButton inverted colours when selected

1.2k views Asked by At

I have a UIButton with a different image for normal and selected state. Also I need to change the tint of the button depending on the app's theme.

But when I set the button to selected State to switch the image, it inverts its colours.

- (void)setLike:(BOOL)selected {
    self.likeButton.selected = selected;
    if (selected) {
        self.likeButton.tintColor = [Theme getTintColor];
    } else {
        self.likeButton.tintColor = [Theme getLightColor];
    }
}

Normal State

enter image description here

Actual Selected

enter image description here

Desired Selected

enter image description here

Note: I can't change the image because this code is used in another places in the app with different selected and unselected images.

- (void)setLike:(BOOL)selected {
    if (selected) {
         [self.likeButton setImage:[UIImage imageNamed:@"Liked"] forState:UIControlStateNormal];
         self.likeButton.tintColor = [Theme getTintColor];
    } else {
         [self.likeButton setImage:[UIImage imageNamed:@"Like"] forState:UIControlStateNormal];
         self.likeButton.tintColor = [Theme getLightBaseColor];
    }
}
2

There are 2 answers

0
egarlock On

I would try to keep track of the state in a property and then have an additional properties for returning the correct image for the current state. You can then set these upon viewDidLoad or viewDidAppear.

I don't know your exact situation so here is an example.

Example:

@property (nonatomic) BOOL isLiked;
...
- (void)viewDidAppear {
    // likeButton
    [self.likeButton setBackgroundImage:[self imageForCurrentState] forState:UIControlStateNormal];
}
...
- (UIImage)imageForCurrentState {
    if (isLiked) {
        return [UIImage imageNamed:@"Liked"];
    } else {
        return [UIImage imageNamed:@"Like"];
    }
}
1
Voyteck On
  1. In Interface Builder find your button, and change it's Type from System to Custom. This should remove the effect of enlarging&reversing image for selected status.
  2. Open your Assets file where both images for Normal and Selected statuses are defined. Set the Render As for Normal image to Original Image, and for Selected image to Template Image. This should result in applying your app's default tint only to selected status.