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

Cha*_*Raj 2 objective-c uiview uicolor ios

这不起作用:

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

PS:要重现这种情况,请在界面生成器中拖动 uiview,将其背景颜色设置为界面生成器中的清除颜色。设置视图的出口,然后使用上面的代码在 viewDidLoad 中进行比较。

这是测试项目的链接:https://drive.google.com/file/d/0B_1hGRxJtrLjMzUyRHZyeV9SYzQ/view ?usp=sharing

这是 Interface Builder 的快照: 在此输入图像描述

Ste*_*fan 5

也许两种颜色都清晰但仍然不一样?alpha 值相同是不够的......

UIColor.clearColor() == UIColor(white: 1.0, alpha: 0.0) // false
UIColor.clearColor() == UIColor(white: 0.0, alpha: 0.0) // true
Run Code Online (Sandbox Code Playgroud)

尝试

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");
Run Code Online (Sandbox Code Playgroud)

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

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