How to compare UIColors? How to compare UIColors? ios ios

How to compare UIColors?


Have you tried [myColor isEqual:someOtherColor] ?


As zoul pointed out in the comments, isEqual: will return NO when comparing colors that are in different models/spaces (for instance #FFF with [UIColor whiteColor]). I wrote this UIColor extension that converts both colors to the same color space before comparing them:

- (BOOL)isEqualToColor:(UIColor *)otherColor {    CGColorSpaceRef colorSpaceRGB = CGColorSpaceCreateDeviceRGB();    UIColor *(^convertColorToRGBSpace)(UIColor*) = ^(UIColor *color) {        if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) == kCGColorSpaceModelMonochrome) {            const CGFloat *oldComponents = CGColorGetComponents(color.CGColor);            CGFloat components[4] = {oldComponents[0], oldComponents[0], oldComponents[0], oldComponents[1]};            CGColorRef colorRef = CGColorCreate( colorSpaceRGB, components );            UIColor *color = [UIColor colorWithCGColor:colorRef];            CGColorRelease(colorRef);            return color;                    } else            return color;    };    UIColor *selfColor = convertColorToRGBSpace(self);    otherColor = convertColorToRGBSpace(otherColor);    CGColorSpaceRelease(colorSpaceRGB);    return [selfColor isEqual:otherColor];}


This might be a bit too late, but CoreGraphics has an easier API to achieve this:

CGColorEqualToColor(myColor.CGColor, [UIColor clearColor].CGColor)

Like the documentation says:

Indicates whether two colors are equal. Two colors are equal if they have equal color spaces and numerically equal color components.

This solves a lot trouble and leaking/custom algorithms.