2016-04-14 54 views
4

我想比較顏色,但我不能使用isEqual方法,因爲我試圖比較UICollectionViewCell的背景顏色。如何快速比較顏色

在這種情況下比較顏色的正確方法是什麼?

if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor) 
{ 
    cell?.layer.backgroundColor = UIColor.redColor().CGColor 
} 
+0

我很抱歉,如果我想的東西比較,但你可以使用cell.backgroundColor,並將它與其他的UIColor。我在一些快速的研究中遇到過這個,如果你只使用CGColors,http://stackoverflow.com/a/8191171/4096655 –

+0

這似乎不工作,雖然 –

+0

http://stackoverflow.com/q/970475/2303865 –

回答

11

嘗試CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool

+0

CGColorEqualToColor在swift3中已棄用 – nilotic

+0

是的,只是使用'==='來代替 –

3

我來到了這個在操場上,我已經分配UICollectionViewCell的backgroundColor屬性用的UIColor然後創建的UIColor從它的layer.backgroundColor CGColor屬性:

let blue = UIColor.blueColor() 

let collectionCell = UICollectionViewCell() 

collectionCell.backgroundColor = blue 

let cellLayerBgrndColor = UIColor(CGColor: collectionCell.layer.backgroundColor!) 

if blue == cellLayerBgrndColor { 

print("equal") // Prints equal 
} 
1
extension CGColor: Equatable { } 
public func ==(lhs: CGColor, rhs: CGColor) -> Bool { 
    return CGColorEqualToColor(lhs,rhs) 
} 
let color1 = UIColor(hue: 0, saturation: 1, brightness: 1, alpha: 1).CGColor 
let color2 = UIColor.redColor().CGColor 

print(color1 == color2) // "true\n" 
0

你可以比較通過調用.description財產等產生的字符串:

// UIColor.red.description -> "UIExtendedSRGBColorSpace 1 0 0 1" 
if(cell!.layer.backgroundColor!.description == UIColor.red.description) 
{ 
    cell?.layer.backgroundColor = UIColor.redColor().CGColor 
} 

但是請注意,色彩空間也必須匹配。

0

斯威夫特3你可以簡單的色彩搭配===

let c1 = UIColor.red.cgColor 
let c2 = UIColor.red.cgColor 

if c1 === c2 { 
    print('Equal') 
}