选中时避免使用UIButton反色

时间:2015-06-25 13:47:21

标签: ios objective-c uibutton selected

我有一个UIButton,其中包含正常和选定状态的不同图像。此外,我需要根据应用程序的主题更改按钮的色调。

但是当我将按钮设置为选择状态以切换图像时,它会反转其颜色。

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

正常状态

enter image description here

实际选择

enter image description here

所需选择

enter image description here

注意:我无法更改图片,因为此代码会在应用中的其他位置使用,具有不同的选定和未选择的图像。

- (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 个答案:

答案 0 :(得分:1)

  1. 在Interface Builder中找到您的按钮,并将其从Type更改为System Custom。这应该消除放大和反转图像以选择状态的效果。
  2. 打开Assets文件,其中定义了Normal和Selected状态的两个图像。将普通图像的Render As设置为Original Image,将所选图像设置为Template Image。这会导致应用程序的默认色调仅应用于选定状态。

答案 1 :(得分:0)

我会尝试跟踪属性中的状态,然后有一个额外的属性来返回当前状态的正确图像。然后,您可以在viewDidLoadviewDidAppear上设置这些内容。

我不知道你的确切情况所以这是一个例子。

示例:

@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"];
    }
}