Search code examples
randomuilabeluicolor

Randomizing the color of a label


So I have a label and I want to be able to press the button I have setup and change the RGB values of the label. Seems simple but I am stumped. Any ideas?

NSInteger r = arc4random()%255;
NSInteger g = arc4random()%255;
NSInteger b = arc4random()%255;

_label.textColor= [UIColor colorWithRed:(arc4random_uniform(r/255.0)) green:(arc4random_uniform(g/255.0)) blue:(arc4random_uniform(b/255.0)) alpha:1] ;

Solution

  • You need to replace

    [UIColor colorWithRed:(arc4random_uniform(r/255.0)) green:(arc4random_uniform(g/255.0)) blue:(arc4random_uniform(b/255.0)) alpha:1] ;
    

    with

    [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1] ;
    

    As you're currently calling arc4_random_uniform() on a random value that's already between 1 and 0 - which is exactly what you need to create a color.