【问题标题】:Change button backgoundColor更改按钮背景颜色
【发布时间】:2015-06-04 06:23:20
【问题描述】:

我正在尝试更改按钮颜色,然后点击它,但它不起作用,因为这样做我必须检测按钮当前必须更改为下一种颜色的颜色。

if (sender.backgroundColor == [UIColor clearColor]) {
    [sender setBackgroundColor:[UIColor grayColor]];
} else if (sender.backgroundColor == [UIColor grayColor]) {
    [sender setBackgroundColor:[UIColor blueColor]];
} else if (sender.backgroundColor == [UIColor blueColor]) {
    [sender setBackgroundColor:[UIColor redColor]];
} else {
    [sender setBackgroundColor:[UIColor clearColor]];
}

但不幸的是,它不起作用。 有谁知道我怎样才能做到这一点?

【问题讨论】:

    标签: ios xcode button background-color


    【解决方案1】:
    UIButton *buttonTapped = sender;
    
    if (buttonTapped.backgroundColor == [UIColor clearColor]) {
      [buttonTapped setBackgroundColor:[UIColor grayColor];
    } else if (buttonTapped.backgroundColor == [UIColor grayColor) {
      [buttonTapped setBackgroundColor:[UIColor blueColor];
    } else if (buttonTapped.backgroundColor == [UIColor blueColor) {
      [buttonTapped setBackgroundColor:[UIColor redColor];
    } else {
      [buttonTapped setBackgroundColor:[UIColor clearColor]];
    }
    

    试试这个?

    【讨论】:

      【解决方案2】:

      这个问题是您使用“==”来比较颜色,它们是对象 - 而不是基元。你想要做的是像这样比较颜色:

      if ([buttonTapped.backgroundColor isEqual: [UIColor clearColor]]) {
        [buttonTapped setBackgroundColor:[UIColor grayColor];
      }
      

      ...等等。

      【讨论】:

        【解决方案3】:
        UIButton *btn = (UIButton*)sender;
        if ([btn.backgroundColor isEqual:someOtherColor]) {
          [buttonTapped setBackgroundColor:[UIColor redColor];
        }
        

        【讨论】:

        • 通常避免只使用代码的答案。考虑添加有助于解释代码的description。谢谢
        猜你喜欢
        • 1970-01-01
        • 2021-06-22
        • 2015-04-03
        • 1970-01-01
        • 2011-06-26
        • 2021-07-05
        相关资源
        最近更新 更多