'How to compare a color in swift
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
}
Solution 1:[1]
Try CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool
.
Solution 2:[2]
Swift 3 or later
CGColorEqualToColor
is deprecated. You can now directly check them for equality:
let color1 = UIColor(hue: 0, saturation: 1, brightness: 1, alpha: 1).cgColor
let color2 = UIColor.red.cgColor
print(color1 == color2) // "true\n"
Original post
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"
Solution 3:[3]
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
}
Solution 4:[4]
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.
Solution 5:[5]
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')
}
Solution 6:[6]
Instead of CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool
need to use if color1.cgColor == UIColor.systemBlue.cgColor { }
which returns Bool
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Inhan |
Solution 2 | |
Solution 3 | Fred Faust |
Solution 4 | Dali |
Solution 5 | |
Solution 6 | Daya Kevin |