如何检查 UIView 的背景颜色是否为 clearColor?

How to check if a UIView's backgroundColor is clearColor?

这不起作用:

if([myView.backgroundColor isEqual:[UIColor clearColor]])
   NSLog("Background is clear");
else
   NSLog("Background is not clear");

P.S:要重现案例,请在界面生成器中拖动一个 uiview,将其背景颜色设置为从界面生成器中清除颜色。设置视图的出口,然后使用上面的代码在 viewDidLoad 中进行比较。

下面是测试项目的link:https://drive.google.com/file/d/0B_1hGRxJtrLjMzUyRHZyeV9SYzQ/view?usp=sharing

这是界面生成器的快照:

您的代码是正确的,只是您的假设不正确。 运行 这些行看看你哪里出错了:

NSLog("view color: %@", myView.backgroundColor);
NSLog("expected color: %@", [UIColor clearColor]);

也许两种颜色都清楚但还是不一样? alpha值相同还不够...

UIColor.clearColor() == UIColor(white: 1.0, alpha: 0.0) // false
UIColor.clearColor() == UIColor(white: 0.0, alpha: 0.0) // true

尝试

if([myView.backgroundColor isEqual:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0]])
   NSLog("Background is clear");
else
   NSLog("Background is not clear");

更好的方法可能是只检查 alpha 是否为 0.0:

CGFloat alpha = CGColorGetAlpha(myView.backgroundColor.CGColor);
if( alpha == 0.0 )
   NSLog("Background is clear");
else
   NSLog("Background is not clear");

你的代码是正确的

UIView *aView = [[UIView alloc] init];
aView.backgroundColor = [UIColor clearColor];

if([aView.backgroundColor isEqual:[UIColor clearColor]]) {
     NSLog(@"Background is clear");
} else {
     NSLog(@"Background is not clear");
}

结果:

2015-07-22 15:22:57.430 APP[1568:24173] Background is clear

更新:界面生成器的默认颜色案例

发件人:UIView Class Reference

@property(nonatomic, copy) UIColor *backgroundColor

Discussion

Changes to this property can be animated. The default value is nil, which results in a transparent background color.

如果您将颜色设置为界面生成器的默认颜色 backgroundColor 属性 将为零,因此与 [UIColor clearColor] 的比较将为假。

您可以更新处理这种情况的代码:

if([self.aView.backgroundColor isEqual:[UIColor clearColor]] ||  self.aView.backgroundColor == nil) {
    NSLog(@"Background is clear");
} else {
    NSLog(@"Background is not clear");
}

更新:来自界面生成器的清晰颜色案例

您可以测试 alpha 值:

CGFloat bgColorAlpha = CGColorGetAlpha(self.aView.backgroundColor.CGColor);

if (bgColorAlpha == 0.0){
    NSLog(@"clear ");
}else{
   NSLog(@"not clear ");
}

2015-07-22 16:56:23.290 APP[1922:38283] clear

更多信息:

How to compare UIColors

Comparing colors in Objective-C

UIColor comparison