如何比较swift中的颜色

问题描述 投票:7回答:6

我想比较颜色,但我不能使用isEqual方法,因为我试图比较UICollectionViewCell背景的颜色。

在这种情况下比较颜色的正确方法是什么?

if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
    cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
ios swift uicollectionviewcell
6个回答
12
投票

试试CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool


3
投票

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

2
投票
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"

2
投票

您可以通过调用.description属性来比较生成的字符串,如:

// UIColor.red.description -> "UIExtendedSRGBColorSpace 1 0 0 1"
if(cell!.layer.backgroundColor!.description == UIColor.red.description)
{
    cell?.layer.backgroundColor = UIColor.redColor().CGColor
}

但请注意,颜色空间也必须匹配。


1
投票

在Swift 3中,您可以简单地将颜色与===进行比较

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

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

0
投票

Swift4

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

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


© www.soinside.com 2019 - 2024. All rights reserved.