Joe
Joe

Reputation: 601

Comparison of text color in UILabel with UIColor fails

I'm trying to compare the text colour in a UIlabel with a UIColor but the result is always false.

The following code produces the result:

color equal 1, 0

I expect both a and b to be equal to 1. Is there another way to do this compare?

    bool a,b;

    UIColor *myColor1, *myColor2;

    myColor1 = [UIColor redColor];
    mainViewController.timerLabel.textColor = [UIColor redColor];

    myColor2 = [UIColor colorWithCGColor:mainViewController.timerLabel.textColor.CGColor];


    a = [[UIColor redColor] isEqual:myColor1];
    b = [[UIColor redColor] isEqual:myColor2];

    NSLog(@"color equal %i, %i",a,b);

Upvotes: 5

Views: 1455

Answers (1)

zaph
zaph

Reputation: 112857

UIColor does not define isEqual, isEqual is inherited from NSObject. Thus isEqual is comparing the addresses of the colors and will fail.

CGColor has a comparison function CGColorEqualToColor():

CGColor *c = myColor.CGColor;

Then the CGColor colors can be compared:

bool colorsEqual = CGColorEqualToColor(myColor1.CGColor, myColor2.CGColor);

Or get the individual components of the two colors and compare then individually using
- (BOOL)getRed:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha

Upvotes: 11

Related Questions