TommyBs TommyBs - 5 months ago 174
iOS Question

Comparing UIColor incorrect only for black and gray

I'm currently trying to compare some UIColor in swift (specifically the colour of an SKLabelNode) and everything works fine except if the colour is Gray or Black. Please note I'm also using the built in colours only

I've tried comparing the UIColor I create to the labelNode.color and labelNode.fontColor (both are set the same) but as I say it always fails for Gray and Black. I've looked at a number of posts that suggest using colour.description etc. and also this post Issue comparing UIColors in Swift

Incidentally if I don't compare the description but the actual color object then Brown also fails.

but the answers from previous posts don't seem to work. Here's a playground example:

let checkColor =

let label = SKLabelNode(text: "foo")
label.fontColor =
print(label.fontColor?.description == checkColor.description)

let checkColor = UIColor.brown

let label = SKLabelNode(text: "foo")
label.fontColor = UIColor.brown
print(label.fontColor? == checkColor) // this returns 'false' for brown when description isn't used

any ideas?

The only way I've found around this is to assign the checkColor variable to another dummy SKLabelNode and compare the 2 fontColor properties to each other like that.


If you try to log you checkColor you'll see that it's of type UIExtendedGrayColorSpace, and your fontColor is of type UIExtendedSRGBColorSpace.

The solution is to init your checkColor with and RGB color (I tried to cast your checkColor as rgb but didn't find a solution). So here is what I got :

let checkColor =
let checkColorRGB = UIColor.init(red: 0, green: 0, blue: 0, alpha: 1)

let label = SKLabelNode(text: "foo")
label.fontColor =
print(label.fontColor == checkColor)
print(label.fontColor == checkColorRGB)

Tested on playground, you'll see that the second print log true