简体   繁体   English

如何比较swift中的颜色

[英]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 . 我试图比较颜色,但我不能使用isEqual方法,因为我试图比较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
}

试试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: 我在操场上想出了这个,我已经用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"

You could compare the strings produced by calling the .description property like: 您可以通过调用.description属性来比较生成的字符串,如:

// 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 === Swift 3中,您可以简单地将颜色与===进行比较

let c1 = UIColor.red.cgColor
let c2 = UIColor.red.cgColor

if c1 === c2 {
   print('Equal')
}

Swift4 Swift4

if UINavigationBar.appearance().tintColor == UIColor.white {  
   DDLog("---112--")
}

2019-03-14 16:22:03.766 UIViewController+Helper.swift.createBackItem[122]:
__---112--


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM