在NSDictionary中存储UIColors并检索它们?

时间:2012-10-01 17:15:38

标签: objective-c ios nsarray uicolor

我需要为给定的索引返回特定的UIColor 我试图基本上将UIColors存储为NSArrays

  

TypeColors = [[NSDictionary alloc] initWithObjectsAndKeys:

     

@“1”,[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.5],[NSNumber numberWithFloat:0.5],[NSNumber   numberWithFloat:0.5],[NSNumber numberWithFloat:1.0],nil],

     

@“5”,[NSArray arrayWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber   numberWithFloat: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]];

它总是让我归零,谁知道为什么? 谢谢!

3 个答案:

答案 0 :(得分: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)

两件事:

1)initWithObjectsAndKeys中的事物顺序是对象,然后是它们的键。是的,这是直观的倒退。

2)密钥不是整数5,而是NSString @"5"

答案 2 :(得分:1)

您需要先将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"];

我将按照以下步骤进行检索

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

希望对你有所帮助......