2014-05-25 49 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),我會用新的隨機值填充它,並將靜態索引設置爲零。 –