objective-cuicolor

Generate a random UIColor


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?


Solution

  • Because you have assigned the colour values to int variables. Use float (or CGFloat) instead. Also (as @stackunderflow's said), the remainder must be taken modulo 256 in order to cover the whole range 0.0 ... 1.0:

    CGFloat red = arc4random() % 256 / 255.0;
    // Or (recommended):
    CGFloat red = arc4random_uniform(256) / 255.0;