我想比較顏色,但我不能使用isEqual
方法,因爲我試圖比較UICollectionViewCell
的背景顏色。如何快速比較顏色
在這種情況下比較顏色的正確方法是什麼?
if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
我想比較顏色,但我不能使用isEqual
方法,因爲我試圖比較UICollectionViewCell
的背景顏色。如何快速比較顏色
在這種情況下比較顏色的正確方法是什麼?
if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
嘗試CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool
。
CGColorEqualToColor在swift3中已棄用 – nilotic
是的,只是使用'==='來代替 –
我來到了這個在操場上,我已經分配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
}
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"
你可以比較通過調用.description
財產等產生的字符串:
// UIColor.red.description -> "UIExtendedSRGBColorSpace 1 0 0 1"
if(cell!.layer.backgroundColor!.description == UIColor.red.description)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
但是請注意,色彩空間也必須匹配。
在斯威夫特3你可以簡單的色彩搭配===
let c1 = UIColor.red.cgColor
let c2 = UIColor.red.cgColor
if c1 === c2 {
print('Equal')
}
我很抱歉,如果我想的東西比較,但你可以使用cell.backgroundColor,並將它與其他的UIColor。我在一些快速的研究中遇到過這個,如果你只使用CGColors,http://stackoverflow.com/a/8191171/4096655 –
這似乎不工作,雖然 –
http://stackoverflow.com/q/970475/2303865 –