Hi, in run time i need to convert UIColor to NSString ..is there any method..any help?
i tried
NSString *colorString = NSStringFromClass([[UIColor redColor] class]);
colorString did not give @"redColor"
Hi, in run time i need to convert UIColor to NSString ..is there any method..any help?
i tried
NSString *colorString = NSStringFromClass([[UIColor redColor] class]);
colorString did not give @"redColor"
What do you want to do that for? Have a look at generic -desciption
method for a start
UIColor* someColor = ...//Initialize color
NSString* colorString = [someColor description];
How about this:
- (NSString *)stringForColor:(UIColor *)color {
CGColorRef c = color.CGColor;
const CGFloat *components = CGColorGetComponents(c);
size_t numberOfComponents = CGColorGetNumberOfComponents(c);
NSMutableString *s = [[[NSMutableString alloc] init] autorelease];
[s appendString:@"{"];
for (size_t i = 0; i < numberOfComponents; ++i) {
if (i > 0) {
[s appendString:@","];
}
[s appendString:[NSString stringWithFormat:@"%f", components[i]]];
}
[s appendString:@"}"];
return s;
}
For example, stringForColor:[UIColor greenColor]
has the result "{0.000000,1.000000,0.000000,1.000000}".
UIColor *color = value;
const CGFloat *components = CGColorGetComponents(color.CGColor);
NSString *colorAsString = [NSString stringWithFormat:@"%f,%f,%f,%f", components[0], components[1], components[2], components[3]];
Done.
If you want to convert the string back to a UIColor object:
NSArray *components = [colorAsString componentsSeparatedByString:@","];
CGFloat r = [[components objectAtIndex:0] floatValue];
CGFloat g = [[components objectAtIndex:1] floatValue];
CGFloat b = [[components objectAtIndex:2] floatValue];
CGFloat a = [[components objectAtIndex:3] floatValue];
UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:a];
Are you storing a UIColor object as an attribute in Core Data? If so, check out my answer to this question: http://stackoverflow.com/questions/2304882/core-data-data-model-attribute-type-for-uicolor/3172363#3172363