2014-10-04 90 views
0

一個項目我已經改變我的背景顏色,三種顏色之一以下方法:隨機選擇的對象 -

- (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

您可以將顏色存儲到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]; 
} 
0

我會成立三個數組。紅,綠,藍各一個。然後使用一個隨機數發生器來選擇一個索引。然後,你插入arrayRed [指數),arrayGreen [索引],數組[藍] arrayBlue [索引]

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

UE中的arc4Random()函數生成索引。這種方法現在允許您輕鬆地向陣列或其他顏色添加更多顏色。

+0

是'index','Index'和'藍'同樣的指數?代碼中也有語法錯誤。 – 2014-10-04 19:43:14

+0

已更新爲清晰 – 2014-10-04 19:45:47

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]); 

所以,選擇[指數]是你的項目

+1

這與Gustavo的方法非常相似,但它應該是'arc4random()%[options count]',否則最後一個項目永遠不會被選中。請注意,根據https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/arc4random.3.html,建議'arc4random_uniform()'超過arc4random()%... '(但在這種情況下可能無關緊要)。 – 2014-10-04 19:45:51