Write an extension to Uicolor:
#import <UIKit/UIKit.h>
@interface Uicolor (color)
+ (uicolor*) colorwithhexstring: (nsstring*) hex;
+ (uicolor*) colorwithhexstring: (nsstring*) hex Withalpha: (cgfloat) Alpha;
@end
Created by Dubai on 15/4/16.
Copyright (c) year Dubai. All rights reserved.
//
#import "Uicolor+fl.h"
@implementation Uicolor (Ali)
+ (uicolor*) colorwithhexstring: (nsstring*) hex
{
nsstring *cstring = [[Hexstringbytrimmingcharactersinset: [Nscharacterset Whitespaceandnewlinecharacterset]] uppercasestring];
//String should be 6 or 8 characters
if ([cString length] <6) return [uicolorgraycolor];
//strip 0X if it appears
if ([cString hasprefix:@ "0X"]) cString = [cStringsubstringfromindex:2];
if ([cString length]! =6) return [uicolorgraycolor];
//separate into R, G, B substrings
nsrange Range;
Range. location =0;
Range. length =2;
nsstring *rstring = [cString substringwithrange: Range];
Range. location =2;
nsstring *gstring = [cString substringwithrange: Range];
Range. location =4;
nsstring *bstring = [cString substringwithrange: Range];
//Scan values
unsigned int R, G, B;
[[nsscannerscannerwithstring: rString] scanhexint:&r];
[[nsscannerscannerwithstring: gstring] scanhexint:&g];
[[nsscannerscannerwithstring: bstring] scanhexint:&b];
return [uicolorcolorwithred:((float) R/255.0f)
Green:((float) G/255.0f)
Blue:((float) b/255.0f)
Alpha:1.0f];
}
+ (uicolor*) colorwithhexstring: (nsstring*) hex Withalpha: (cgfloat) Alpha
{
nsstring *cstring = [[Hexstringbytrimmingcharactersinset: [Nscharacterset Whitespaceandnewlinecharacterset]] uppercasestring];
//String should be 6 or 8 characters
if ([cString length] <6) return [uicolorgraycolor];
//strip 0X if it appears
if ([cString hasprefix:@ "0X"]) cString = [cStringsubstringfromindex:2];
if ([cString length]! =6) return [uicolorgraycolor];
//separate into R, G, B substrings
nsrange Range;
Range. location =0;
Range. length =2;
nsstring *rstring = [cString substringwithrange: Range];
Range. location =2;
nsstring *gstring = [cString substringwithrange: Range];
Range. location =4;
nsstring *bstring = [cString substringwithrange: Range];
//Scan values
unsigned int R, G, B;
[[nsscannerscannerwithstring: rString] scanhexint:&r];
[[nsscannerscannerwithstring: gstring] scanhexint:&g];
[[nsscannerscannerwithstring: bstring] scanhexint:&b];
return [uicolorcolorwithred:((float) R/255.0f)
Green:((float) G/255.0f)
Blue:((float) b/255.0f)
Alpha: Alpha];
}
@end
When using the import header file: Directly can be used:
self. Segcontrol . BackgroundColor = [uicolorcolorwithhexstring:@ "47a5d6"];
It's OK!
IOS Hex Configuration Background color