2012-10-01 32 views
3

我需要爲給定索引返回特定的UIColor。
我想的UIColors基本上存儲爲NSArrays在NSDictionary中存儲UIColors並檢索它們?

TypeColors = [[NSDictionary中的alloc] initWithObjectsAndKeys:

@ 「1」,[NSArray的arrayWithObjects:[NSNumber的numberWithFloat:0.5],[的NSNumber numberWithFloat:0.5],[NSNumber的 numberWithFloat:0.5],[NSNumber的numberWithFloat:1.0],零],

@ 「5」,[NSArray的arrayWithObjects:[NSNumber的numberWithFloat:1.0],[的NSNumbernumberWithFloat:0.5],[NSNumber numberWithFloat:0.1],[NSNumber numberWithFloat:1.0],nil] ,nil]; //無表示對象和鍵的結尾。

在這裏,我想從字典檢索的UIColor回:

a = 5; 
NSArray* colorArray = [TypeColors objectForKey:a]; 
UIColor* color = [UIColor colorWithRed:[colorArray objectAtIndex:0] 
green:[colorArray objectAtIndex:1] blue:[colorArray objectAtIndex:2] 
alpha:[colorArray objectAtIndex:3]]; 

它總是返回我是零,任何人都知道這是爲什麼? 謝謝!

回答

1

將其更改爲

UIColor* color = [UIColor colorWithRed:[[colorArray objectAtIndex:0] floatValue] 
green:[[colorArray objectAtIndex:1] floatValue] blue:[[colorArray objectAtIndex:2] floatValue] 
alpha:[[colorArray objectAtIndex:3] floatValue]]; 

的參數發送有CGFloat的,而不是NSNumber的

1

兩件事情:

1)的事物initWithObjectsAndKeys的順序是對象,然後他們的鑰匙。是的,這是直觀的倒退。

2)密鑰不是整數5而是NSString@"5"

2

您需要將您的UIColor轉換爲NSString的第一前將其保存在字典如下:

-(NSString *)convertColorToString :(UIColor *)colorname 
    { 
    if(colorname==[UIColor whiteColor]) 
    { 
     colorname= [UIColor colorWithRed:1 green:1 blue:1 alpha:1]; 
    } 
    else if(colorname==[UIColor blackColor]) 
    { 
     colorname= [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; 
    } 
    else 
    { 
     colorname=colorname; 
    } 
    CGColorRef colorRef = colorname.CGColor; 
    NSString *colorString; 
    colorString=[CIColor colorWithCGColor:colorRef].stringRepresentation; 
    return colorString; 
} 

,當你想獲取從字典中的值比你需要將字符串轉換爲顏色遵循

-(UIColor *)convertStringToColor :(NSDictionary *)dicname :(NSString *)keyname 
{ 
    CIColor *coreColor = [CIColor colorWithString:[dicname valueForKey:keyname]]; 
    UIColor *color = [UIColor colorWithRed:coreColor.red green:coreColor.green blue:coreColor.blue alpha:coreColor.alpha]; 
    //NSLog(@"color name :%@",color); 
    return color; 
} 

EXA:

這裏dicSaveAllUIupdate是我的字典,我在它救了我的觀點的背景顏色。

[dicSaveAllUIupdate setObject:[self convertColorToString: self.view.backgroundColor] forKey:@"MAINVW_BGCOLOR"]; 

,我會retrive它遵循

self.view.backgroundColor=[self convertStringToColor:retrievedDictionary:@"MAINVW_BGCOLOR"]; 

希望這對您有所幫助...

相關問題