2014-09-29 31 views
1

您好我是目標C新和我有很難與數組索引的NSMutableDictionary以作爲值的NSArray

我需要創建一個的NSMutableDictionary其中包含5種的RGB顏色。
每種顏色將包含隨機生成的3個組件,alpha值將固定爲1.0。
這應該在for循環中。

由端我需要有

  1. 鍵:first_col _________值:0.13,0.75,0.91,1.0
  2. 鍵:second_col ______值:0.25,0.06,0.48,1.0
  3. 鍵:third_col ________值:0.86,0.12,0.55,1.0
  4. 鍵:_______________值:
  5. 鍵:_______________值:

謝謝

+1

難道不容易用UIColor代替數組? – Pochi 2014-09-29 08:10:49

+2

到目前爲止您嘗試了什麼?具體來說,你有什麼問題? – JoeFryer 2014-09-29 08:12:04

回答

0

試試這個答案..

- (void)viewDidLoad 
    { 
     [super viewDidLoad]; 
     NSMutableDictionary *dictonary; 
     NSMutableArray *temp=[NSMutableArray array]; 
     for (int i=0; i<5; i++) 
     { 
      dictonary=[NSMutableDictionary dictionary]; 
      [dictonary setObject:[self getColor:i] forKey:[NSString stringWithFormat:@"color%d",i]]; 
      [temp addObject:dictonary]; 
     } 
     NSLog(@"%@",temp); 

    } 
    -(UIColor *)getColor:(NSInteger)index 
    { 
     UIColor *color; 
     color=[self returnColor:index ]; 
     return color; 
    } 
    -(UIColor *)returnColor:(int)passedIndex 
    { 


     CGFloat red = arc4random()%255; 
     CGFloat green =arc4random()%255; 
     CGFloat blue = arc4random()%255; 

     UIColor *color; 
     switch (passedIndex) { 
      case 0: 
       color=[UIColor colorWithRed:(red/255) green:(green/255) blue:(blue/255) alpha:1.0]; 
       break; 
      case 1: 
       color=[UIColor colorWithRed:(red/255) green:(green/255) blue:(blue/255) alpha:1.0]; 
       break; 
      case 2: 
       color=[UIColor colorWithRed:(red/255) green:(green/255) blue:(blue/255) alpha:1.0]; 
       break; 
      case 3: 
       color=[UIColor colorWithRed:(red/255) green:(green/255) blue:(blue/255) alpha:1.0]; 
       break; 
      case 4: 
       color=[UIColor colorWithRed:(red/255) green:(green/255) blue:(blue/255) alpha:1.0]; 
       break; 
      case 5: 
       color=[UIColor colorWithRed:(red/255) green:(green/255) blue:(blue/255) alpha:1.0]; 
       break; 
      default: 
       break; 
     } 
     return color; 
    } 
+0

謝謝@karthikeyan – Vaki 2014-09-29 13:17:36

+0

如果這個答案幫助你,標記爲正確的答案 – karthikeyan 2014-09-29 13:33:15

+0

我是一個新鮮:)。再次感謝你 – Vaki 2014-09-29 13:38:26

0

做這樣

NSDictionary * colorsDictionary = [[NSDictionary alloc]initWithObjectsAndKeys: 
          [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0],@"color1", 
          [UIColor colorWithRed:(260/255.0) green:(97/255.0) blue:(105/255.0) alpha:1.0],@"color2", 
          [UIColor colorWithRed:(106/255.0) green:(97/255.0) blue:(205/255.0) alpha:1.0],@"color2", 
          [UIColor colorWithRed:(10/255.0) green:(97/255.0) blue:(55/255.0) alpha:1.0],@"color3", 
          nil]; 
+0

謝謝@iRaki。這工作完美。如果我想添加到字典數組* col_components(對於一般情況)它應該如何[CGFloat col_components],@「color1」 – Vaki 2014-09-29 13:23:44

相關問題