user3196904 user3196904 - 3 months ago 17
Objective-C Question

Generate a random UIColor

I try to get a random colors 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?

P.S. Sorry for my english )

Answer

Because you have assigned the colour values to int variables. Use float (or CGFloat) instead:

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

(See also stackunderflow's answer about the range of possible values.)

Comments