AJFIN AJFIN - 1 month ago 16
iOS Question

Random color in iOS

I want to make my Navbar a different color each time its loaded. I have placed the following code in my viewDidApear:

CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

self.navigationBar.barTintColor = color;


the problem is that the color range is too wide.

I would like it to only select the colors that you see in this photo:

enter image description here

Is it possible using this code? + if not how would i create a similar one that chooses a random color from a few that I have defined.

Thanks you for you help.

Answer

Here's a copy / paste solution using your exact colors.

// Declare somewhere in your code
typedef struct _Color {
    CGFloat red, green, blue;
} Color;

static Color _colors[12] = {
    {237, 230, 4},  // Yellow just to the left of center
    {158, 209, 16}, // Next color clockwise (green)
    {80, 181, 23},
    {23, 144, 103},
    {71, 110, 175},
    {159, 73, 172},
    {204, 66, 162},
    {255, 59, 167},
    {255, 88, 0},
    {255, 129, 0},
    {254, 172, 0},
    {255, 204, 0}
};

- (UIColor *)randomColor {
    Color randomColor = _colors[arc4random_uniform(12)];
    return [UIColor colorWithRed:(randomColor.red / 255.0f) green:(randomColor.green / 255.0f) blue:(randomColor.blue / 255.0f) alpha:1.0f];
}

NOTE: You should use arc4random_uniform() instead of arc4random() to avoid modulo bias (although not all that important in this case).

Comments