I am trying to compare colors but I cannot use the isEqual method because I am trying to compare the color of the background of a UICollectionViewCell.
What is the correct way to compare colors in this situation?
if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
Try CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool.
I've come up with this in a playground, I've assigned the backgroundColor property of the UICollectionViewCell with a UIColor and then created a UIColor from it's layer.backgroundColor CGColor property:
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"
You could compare the strings produced by calling the .description property like:
// UIColor.red.description -> "UIExtendedSRGBColorSpace 1 0 0 1"
if(cell!.layer.backgroundColor!.description == UIColor.red.description)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
But note that colorspace must also match.
In Swift 3 you can simply compare the colors with ===
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--
来源:https://stackoverflow.com/questions/36612843/how-to-compare-a-color-in-swift