Inside the Uicolor+hex.h
#import <UIKit/UIKit.h>@interface uicolor (Hex)+ (Uicolor *) Colorwithhexstring: ( NSString *) color; @end
Inside the UICOLOR+HEX.M
#import "uicolor+hex.h"@implementationUicolor (Hex)#pragmaMark-color Convert hex color in iOS to uicolor+ (Uicolor *) colorwithhexstring: (NSString *) hexstring{NSString*cstring =[[HexString Stringbytrimmingcharactersinset:[nscharacterset Whitespaceandnewlinecharacterset]] Uppercasestring]; //hexstring should be 6 to 8 characters if([cString Length] <6) { return[Uicolor Clearcolor]; } //If the hexstring has the @ "0X" prefix if([cString Hasprefix:@"0X"]) cString= [CString Substringfromindex:2]; //If the hexstring has the @ "#" prefix if([cString Hasprefix:@"#"]) cString= [CString Substringfromindex:1]; if([cString length]! =6) return[Uicolor Clearcolor]; //RGB ConversionNsrange Range; Range.location=0; Range.length=2; //RNSString *rstring =[cString Substringwithrange:range]; //GRange.location =2; NSString*gstring =[cString Substringwithrange:range]; //BRange.location =4; NSString*bstring =[cString Substringwithrange:range]; //UnsignedintR, G, B; [[Nsscanner scannerwithstring:rstring] Scanhexint:&R]; [[Nsscanner scannerwithstring:gstring] Scanhexint:&G]; [[Nsscanner scannerwithstring:bstring] Scanhexint:&b]; return[Uicolor colorwithred: ((float) R/255.0f) Green: ((float) G/255.0f) Blue: ((float) b/255.0f) Alpha:1.0f];}@end
How to use:
// 1. Add header file #import " uicolor+hex.h " // 2. Where needed [uicolor colorwithhexstring:@ "hex"] // eg: [Self.view setbackgroundcolor:[uicolor colorwithhexstring:@ "#11489B"];
IOS 16 binary color values converted to Uicolor