2015-03-31 94 views
0

我想改变一个按钮的颜色,然后我点击它,但它不工作,因为这样做,我必须检测哪个颜色的按钮目前必须改变到下一个颜色。更改按钮backgoundColor

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

但不幸的是它不起作用。 有谁知道我该如何做这项工作?

回答

0
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]]; 
} 

试试这个吗?

0

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

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

...等等。

0
UIButton *btn = (UIButton*)sender; 
if ([btn.backgroundColor isEqual:someOtherColor]) { 
    [buttonTapped setBackgroundColor:[UIColor redColor]; 
} 
+0

通常避免代码的答案。考虑添加一个'description'来帮助解释你的代码。谢谢 – MickyD 2015-03-31 04:05:53