2012-10-01 33 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"]; 

希望这对您有所帮助...

相关问题