2014-05-25 51 views
0
+ (UIColor *)randomColor 
{ 
    static NSMutableArray * __colors; 
    if (__colors == nil) { 
     __colors = [[NSMutableArray alloc] initWithObjects:[UIColor redColor], 
         [UIColor orangeColor], 
         [UIColor yellowColor], 
         [UIColor blueColor], 
         [UIColor greenColor], 
         [UIColor purpleColor], nil]; 

    } 
    static NSInteger index = 0; 

    UIColor *color = __colors[index]; 
    index = index < 5 ? index + 1 : 0; 
    return color; 
} 

在我的应用程序中,我有一个按钮,调用它来随机更改它的背景颜色。颜色随机变化的崩溃

一旦循环通过颜色崩溃与此:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array' 

如何调整我的代码来解决这个问题有什么建议?

编辑:

我正在使用计时器来循环颜色。下面是它是否有助于:

- (void)startCountdown 
{ 
    _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:YES]; 
} 

- (void)advanceTimer:(NSTimer *)timer 
{ 
    self.button.backgroundColor = [UIColor randomColor]; 
} 

编辑:

以上方法是我现在使用的一个。

它是伟大的工作,到目前为止,但有一点我想补充的是:

在一个视图中我可能有多个按钮或图像,将有背景的改变颜色。

现在我有3个视图。其中只有2人正在改变,但没有骑自行车穿过所有的颜色,这意味着2只能获得3种颜色。

回答

0

如果要循环显示颜色,可以使用static integer作为索引。

+ (UIColor *)randomColor 
{ 

    static NSMutableArray * __colors; 
    if (__colors == nil) { 
     __colors = [[NSMutableArray alloc] initWithObjects:[UIColor redColor], 
        [UIColor orangeColor], 
        [UIColor yellowColor], 
        [UIColor blueColor], 
        [UIColor greenColor], 
        [UIColor purpleColor], nil]; 

    } 
    static NSInteger index = 0; 

    UIColor *color = __colors[index]; 
    index = index < 5 ? index + 1 : 0; 
    return color; 
} 
+0

这有帮助,谢谢!我确实看到一件很有趣的事情。我将有多个按钮,改变背景颜色。现在我有2个连线了。每个人只获得3种颜色。我希望每个旋转通过我添加在我的阵列中的许多颜色,而不是分开。为什么我的颜色在我的按钮之间分裂,每个颜色都没有得到所有的颜色? –

+0

你可以使用'__colors [(index ++)%__ colors.count]',但是这看起来不像他想要的,他想要随机的颜色,而不是顺序的颜色,并且在获得新的随机颜色之前需要一整个周期。 –

2

一旦你的颜色用完你的数组是空的,并且索引0超出了数组的数值范围。

+0

那么我如何得到它来循环呢? –

+0

您可以检查数组数是否为零,然后重新创建它,但您可能想要找到更有效的方法 - 删除/创建相当昂贵。 –

+0

从我收集的内容中,您需要随机的颜色,但在获得新颜色之前需要完整的颜色循环。我会创建一个唯一索引的静态C数组,并用一个静态整数迭代它。一旦迭代完成(index == count),我会用新的随机值填充它,并将静态索引设置为零。 –