我想比较颜色,但我不能使用isEqual
方法,因为我试图比较UICollectionViewCell
背景的颜色。
在这种情况下比较颜色的正确方法是什么?
if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
试试CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool
。
我在操场上想出了这个,我已经用UIColor分配了UICollectionViewCell的backgroundColor属性,然后从它的layer.backgroundColor CGColor属性创建了一个UIColor:
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
}
但请注意,颜色空间也必须匹配。
在Swift 3中,您可以简单地将颜色与===
进行比较
let c1 = UIColor.red.cgColor
let c2 = UIColor.red.cgColor
if c1 === c2 {
print('Equal')
}
Swift4
if UINavigationBar.appearance().tintColor == UIColor.white {
DDLog("---112--")
}
2019-03-14 16:22:03.766 UIViewController+Helper.swift.createBackItem[122]:
__---112--