Generate a random UIColor

Tatiana Mudryak picture Tatiana Mudryak · Jan 15, 2014 · Viewed 21.4k times · Source

I try to get a random color for UILabel...

- (UIColor *)randomColor
{
    int red = arc4random() % 255 / 255.0;
    int green = arc4random() % 255 / 255.0;
    int blue = arc4random() % 255 / 255.0;
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
    NSLog(@"%@", color);
    return color;
}

And use it:

[mat addAttributes:@{NSForegroundColorAttributeName : [self randomColor]} range:range];

But color is always black. What is wrong?

Answer

kkodev picture kkodev · May 7, 2014
[UIColor colorWithHue:drand48() saturation:1.0 brightness:1.0 alpha:1.0];

or in Swift:

UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)

Feel free to randomise or adjust saturation and brightness to your liking.