I need to convert UIColor
to an NSString
of the color name.
I tried:
NSString *colorString = NSStringFromClass([[UIColor redColor] class]);
But colorString
did not give @"redColor".
From UIColor to Hex in Swift To convert a UIColor instance to a hex value, we define a convenience method, toHex(alpha:) . The method accepts one parameter of type Bool , which indicates whether the alpha value should be included in the string that is returned from the method.
UIColor provides a list of class properties that create adaptable and fixed colors such as blue, green, purple, and more. UIColor also offers properties to specify system-provided colors for UI elements such as labels, text, and buttons.
In Objective-C, we use this code to set RGB color codes for views: #define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0] view.
The CIColor
class contains color values and the color space for which the color values are valid.
https://developer.apple.com/documentation/coreimage/cicolor
// UIColor to NSString
CGColorRef colorRef = [UIColor grayColor].CGColor;
NSString *colorString = [CIColor colorWithCGColor:colorRef].stringRepresentation;
// NSString to UIColor
CIColor *coreColor = [CIColor colorWithString:@"0.5 0.5 0.5 1.0"];
UIColor *color = [UIColor colorWithCIColor:coreColor];
-----------------Warning-----------
If You Want Support All Devices The Way Mentioned Above to Convert NSString to UIColor Will Not Work On All Devices.
stringRepresentation
Returns a formatted string that specifies the components of the color.
The string representation always has four components—red, green, blue, and alpha.
https://developer.apple.com/documentation/coreimage/cicolor/1437910-stringrepresentation
colorWithString:
Creates a color object using the RGBA color component values specified by a string.
https://developer.apple.com/documentation/coreimage/cicolor/1438059-colorwithstring
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: Core Data data model: attribute type for UIColor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With