我想比较颜色,但我不能使用isEqual
方法,因为我试图比较UICollectionViewCell
的背景颜色。如何快速比较颜色
在这种情况下比较颜色的正确方法是什么?
if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
我想比较颜色,但我不能使用isEqual
方法,因为我试图比较UICollectionViewCell
的背景颜色。如何快速比较颜色
在这种情况下比较颜色的正确方法是什么?
if(cell!.layer.backgroundColor! == UIColor.redColor().CGColor)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
尝试CGColorEqualToColor(_ color1: CGColor!, _ color2: CGColor!) -> Bool
。
CGColorEqualToColor在swift3中已弃用 – nilotic
是的,只是使用'==='来代替 –
我来到了这个在操场上,我已经分配UICollectionViewCell的backgroundColor属性用的UIColor然后创建的UIColor从它的layer.backgroundColor CGColor属性:
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"
你可以比较通过调用.description
财产等产生的字符串:
// UIColor.red.description -> "UIExtendedSRGBColorSpace 1 0 0 1"
if(cell!.layer.backgroundColor!.description == UIColor.red.description)
{
cell?.layer.backgroundColor = UIColor.redColor().CGColor
}
但是请注意,色彩空间也必须匹配。
在斯威夫特3你可以简单的色彩搭配===
let c1 = UIColor.red.cgColor
let c2 = UIColor.red.cgColor
if c1 === c2 {
print('Equal')
}
我很抱歉,如果我想的东西比较,但你可以使用cell.backgroundColor,并将它与其他的UIColor。我在一些快速的研究中遇到过这个,如果你只使用CGColors,http://stackoverflow.com/a/8191171/4096655 –
这似乎不工作,虽然 –
http://stackoverflow.com/q/970475/2303865 –