How to compare a color in swift

ⅰ亾dé卋堺 提交于 2019-12-05 05:05:50

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--


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!