随机选择Obj-C中的项目

时间:2014-10-04 19:27:51

标签: objective-c

我有以下方法将背景颜色更改为三种颜色之一:

- (void) setBackgroundOfView {
    // change the background color
    UIColor *feijoa = [UIColor colorWithRed:0.565 green:0.82 blue:0.478 alpha:1]; /*#90d17a*/
    UIColor *turquoise = [UIColor colorWithRed:0.2 green:0.78 blue:0.773 alpha:1]; /*#33c7c5*/
    UIColor *lavendar = [UIColor colorWithRed:0.765 green:0.541 blue:0.898 alpha:1] /*#c38ae5*/
    UIColor *randomColor = random.choose(feijoa, turquoise, lavendar) // in pseudocode
}

执行random.choose(feijoa, turquoise, lavendar)的正确方法是什么?

3 个答案:

答案 0 :(得分:3)

您可以将颜色存储到NSArray中并随机选择其中一种颜色:

#include <stdlib.h>

- (void) setBackgroundOfView {
    // change the background color
    UIColor *feijoa = [UIColor colorWithRed:0.565 green:0.82 blue:0.478 alpha:1]; /*#90d17a*/
    UIColor *turquoise = [UIColor colorWithRed:0.2 green:0.78 blue:0.773 alpha:1]; /*#33c7c5*/
    UIColor *lavendar = [UIColor colorWithRed:0.765 green:0.541 blue:0.898 alpha:1] /*#c38ae5*/

    NSArray *colors = @[feijoa, turquoise, lavendar];
    int index = arc4random_uniform(colors.count);
    UIColor *randomColor = colors[index];
}

答案 1 :(得分:1)

您有一系列结果:

  UIColor *feijoa = [UIColor colorWithRed:0.565 green:0.82 blue:0.478 alpha:1]; /*#90d17a*/
  UIColor *turquoise = [UIColor colorWithRed:0.2 green:0.78 blue:0.773 alpha:1]; /*#33c7c5*/
  UIColor *lavendar = [UIColor colorWithRed:0.765 green:0.541 blue:0.898 alpha:1] /*#c38ae5*/

你需要随机选择一个。将结果放入数组中:

NSArray *choices = @[feijoa, turquoise, lavender];

然后选择一个随机索引:

int index = arc4random() % ([choices count]);

所以,选择[index]是你的项目

答案 2 :(得分:0)

我会设置三个数组。红色,绿色,蓝色各一个。然后使用随机数生成器来选择索引。然后插入arrayRed [index],arrayGreen [Index],array [Blue] arrayBlue [Index]

 UIColor *feijoa = [UIColor colorWithRed:arrayRed[index) green:arrayGreen[Index] blue:arrayBlue[Index] alpha:1];

使用arc4Random()函数生成索引。此方法现在允许您为阵列添加更多颜色或轻松添加更多颜色。