簡體   English   中英

如何檢查UIView的backgroundColor是否為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");

PS:要重現這種情況,請在界面構建器中拖動uiview,將其背景色設置為從界面構建器中清除顏色。 設置視圖的出口,然后使用上面的代碼在viewDidLoad中對其進行比較。

這是測試項目的鏈接: https : //drive.google.com/file/d/0B_1hGRxJtrLjMzUyRHZyeV9SYzQ/view?usp=sharing

這是Interface Builder的快照: 在此處輸入圖片說明

也許兩種顏色都清晰但仍然不一樣? 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]背景清晰

更新:“界面”構建器中默認顏色的情況

來自: UIView類參考

@property(nonatomic, copy) UIColor *backgroundColor

討論區

可以對此屬性進行更改。 默認值為nil,這將導致透明的背景色。

如果從接口構建器將color設置為默認顏色,則backgroundColor屬性將為nil,因此與[UIColor clearColor]的比較將為false。

您可以在這種情況下更新代碼的句柄:

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]清除

更多信息:

如何比較UIColors

在Objective-C中比較顏色

UIColor比較

您的代碼是正確的,只是假設有誤。 運行以下行以查看您出了什么問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM