¿Cómo puedo crear un UIColor a partir de una cadena hexagonal?

¿Cómo puedo crear un UIColor partir de un formato de cadena hexadecimal , como #00FF00 ?

He encontrado que la forma más sencilla de hacer esto es con una macro. Simplemente inclúyalo en su encabezado y estará disponible durante todo el proyecto.

 #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] 

macro uicolor con valores hexadecimales

También versión formateada de este código:

 #define UIColorFromRGB(rgbValue) \ [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \ blue:((float)((rgbValue & 0x0000FF) >> 0))/255.0 \ alpha:1.0] 

Uso:

 label.textColor = UIColorFromRGB(0xBC1128); 

Una solución concisa:

 // Assumes input like "#00FF00" (#RRGGBB). + (UIColor *)colorFromHexString:(NSString *)hexString { unsigned rgbValue = 0; NSScanner *scanner = [NSScanner scannerWithString:hexString]; [scanner setScanLocation:1]; // bypass '#' character [scanner scanHexInt:&rgbValue]; return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0]; } 

Tengo una solución que es 100% compatible con las cadenas de formato hexadecimal utilizadas por Android, que encontré muy útil cuando se hace desarrollo móvil multiplataforma. Me permite usar un paladar de color para ambas plataformas. Siéntase libre de reutilizar sin atribución, o bajo la licencia de Apache, si lo prefiere.

 #import "UIColor+HexString.h" @interface UIColor(HexString) + (UIColor *) colorWithHexString: (NSString *) hexString; + (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length; @end @implementation UIColor(HexString) + (UIColor *) colorWithHexString: (NSString *) hexString { NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString]; CGFloat alpha, red, blue, green; switch ([colorString length]) { case 3: // #RGB alpha = 1.0f; red = [self colorComponentFrom: colorString start: 0 length: 1]; green = [self colorComponentFrom: colorString start: 1 length: 1]; blue = [self colorComponentFrom: colorString start: 2 length: 1]; break; case 4: // #ARGB alpha = [self colorComponentFrom: colorString start: 0 length: 1]; red = [self colorComponentFrom: colorString start: 1 length: 1]; green = [self colorComponentFrom: colorString start: 2 length: 1]; blue = [self colorComponentFrom: colorString start: 3 length: 1]; break; case 6: // #RRGGBB alpha = 1.0f; red = [self colorComponentFrom: colorString start: 0 length: 2]; green = [self colorComponentFrom: colorString start: 2 length: 2]; blue = [self colorComponentFrom: colorString start: 4 length: 2]; break; case 8: // #AARRGGBB alpha = [self colorComponentFrom: colorString start: 0 length: 2]; red = [self colorComponentFrom: colorString start: 2 length: 2]; green = [self colorComponentFrom: colorString start: 4 length: 2]; blue = [self colorComponentFrom: colorString start: 6 length: 2]; break; default: [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid. It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString]; break; } return [UIColor colorWithRed: red green: green blue: blue alpha: alpha]; } + (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length { NSString *substring = [string substringWithRange: NSMakeRange(start, length)]; NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring]; unsigned hexComponent; [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent]; return hexComponent / 255.0; } @end 

Hay una buena publicación sobre cómo abordar la cuestión del OP de extraer un UIColor de una cadena hexagonal. La solución presentada a continuación es diferente de otras porque admite valores de cadena que pueden incluir ‘0x’ o ‘#’ prefijados a la representación de cadena hexadecimal … (ver uso)

Aquí está el bit principal …

 - (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha { // Convert hex string to an integer unsigned int hexint = [self intFromHexString:hexStr]; // Create color object, specifying alpha as well UIColor *color = [UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255 green:((CGFloat) ((hexint & 0xFF00) >> 8))/255 blue:((CGFloat) (hexint & 0xFF))/255 alpha:alpha]; return color; } 

Método de ayuda …

 - (unsigned int)intFromHexString:(NSString *)hexStr { unsigned int hexInt = 0; // Create scanner NSScanner *scanner = [NSScanner scannerWithString:hexStr]; // Tell scanner to skip the # character [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]]; // Scan hex value [scanner scanHexInt:&hexInt]; return hexInt; } 

Uso:

 NSString *hexStr1 = @"123ABC"; NSString *hexStr2 = @"#123ABC"; NSString *hexStr3 = @"0x123ABC"; UIColor *color1 = [self getUIColorObjectFromHexString:hexStr1 alpha:.9]; NSLog(@"UIColor: %@", color1); UIColor *color2 = [self getUIColorObjectFromHexString:hexStr2 alpha:.9]; NSLog(@"UIColor: %@", color2); UIColor *color3 = [self getUIColorObjectFromHexString:hexStr3 alpha:.9]; NSLog(@"UIColor: %@", color3); 

Artículo completo de referencia

Swift 2+

He portado esta solución a Swift 2.2. Tenga en cuenta que he cambiado el parámetro alpha a un valor opcional con un conjunto predeterminado en 1.0. También actualicé el tipo int a UInt32 según lo requerido por la clase NSScanner en Swift 2.2.

 func colorWithHexString(hexString: String, alpha:CGFloat? = 1.0) -> UIColor { // Convert hex string to an integer let hexint = Int(self.intFromHexString(hexString)) let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0 let green = CGFloat((hexint & 0xff00) >> 8) / 255.0 let blue = CGFloat((hexint & 0xff) >> 0) / 255.0 let alpha = alpha! // Create color object, specifying alpha as well let color = UIColor(red: red, green: green, blue: blue, alpha: alpha) return color } func intFromHexString(hexStr: String) -> UInt32 { var hexInt: UInt32 = 0 // Create scanner let scanner: NSScanner = NSScanner(string: hexStr) // Tell scanner to skip the # character scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#") // Scan hex value scanner.scanHexInt(&hexInt) return hexInt } 

Swift 4+

Usando la misma lógica con los cambios aplicados para swift 4,

 func colorWithHexString(hexString: String, alpha:CGFloat? = 1.0) -> UIColor { // Convert hex string to an integer let hexint = Int(self.intFromHexString(hexStr: hexString)) let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0 let green = CGFloat((hexint & 0xff00) >> 8) / 255.0 let blue = CGFloat((hexint & 0xff) >> 0) / 255.0 let alpha = alpha! // Create color object, specifying alpha as well let color = UIColor(red: red, green: green, blue: blue, alpha: alpha) return color } func intFromHexString(hexStr: String) -> UInt32 { var hexInt: UInt32 = 0 // Create scanner let scanner: Scanner = Scanner(string: hexStr) // Tell scanner to skip the # character scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#") // Scan hex value scanner.scanHexInt32(&hexInt) return hexInt } 

Referencias hexadecimales de color

Códigos y nombres de colores HTML

Códigos de color Hex Color

Esta es una función que toma una cadena hexadecimal y devuelve un UIColor.
(Puede ingresar cadenas hexagonales con cualquier formato: #ffffff o ffffff )

Uso:

 var color1 = hexStringToUIColor("#d3d3d3") 

Swift 4:

 func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } 

Swift 3:

 func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } 

Swift 2:

 func hexStringToUIColor (hex:String) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(cString.startIndex.advancedBy(1)) } if ((cString.characters.count) != 6) { return UIColor.grayColor() } var rgbValue:UInt32 = 0 NSScanner(string: cString).scanHexInt(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } 


Fuente: arshad / gist: de147c42d7b3063ef7bc

Usa esta categoría:

en el archivo UIColor + Hexadecimal.h

 #import  @interface UIColor(Hexadecimal) + (UIColor *)colorWithHexString:(NSString *)hexString; @end 

en el archivo UIColor + Hexadecimal.m

 #import "UIColor+Hexadecimal.h" @implementation UIColor(Hexadecimal) + (UIColor *)colorWithHexString:(NSString *)hexString { unsigned rgbValue = 0; NSScanner *scanner = [NSScanner scannerWithString:hexString]; [scanner setScanLocation:1]; // bypass '#' character [scanner scanHexInt:&rgbValue]; return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0]; } @end 

En Class quieres usarlo:

 #import "UIColor+Hexadecimal.h" 

y:

 [UIColor colorWithHexString:@"#6e4b4b"]; 

Una gran implementación de Swift (actualizada para Xcode 7) usando extensiones, reunidas desde una variedad de respuestas y lugares diferentes. También necesitarás las extensiones de cadena al final.

Utilizar:

 let hexColor = UIColor(hex: "#00FF00") 

NOTA: Agregué una opción para 2 dígitos adicionales al final del valor hexadecimal estándar de 6 dígitos para un canal alfa (pase en el valor de 0099 ). Si esto te ofende, solo quítalo. Puede implementarlo para pasar un parámetro alfa opcional.

Extensión:

 extension UIColor { convenience init(var hex: String) { var alpha: Float = 100 let hexLength = hex.characters.count if !(hexLength == 7 || hexLength == 9) { // A hex must be either 7 or 9 characters (#RRGGBBAA) print("improper call to 'colorFromHex', hex length must be 7 or 9 chars (#GGRRBBAA)") self.init(white: 0, alpha: 1) return } if hexLength == 9 { // Note: this uses String subscripts as given below alpha = hex[7...8].floatValue hex = hex[0...6] } // Establishing the rgb color var rgb: UInt32 = 0 let s: NSScanner = NSScanner(string: hex) // Setting the scan location to ignore the leading `#` s.scanLocation = 1 // Scanning the int into the rgb colors s.scanHexInt(&rgb) // Creating the UIColor from hex int self.init( red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: CGFloat(alpha / 100) ) } } 

Extensiones de cadena:
Fuente de flotación
Fuente de subíndice

 extension String { /** Returns the float value of a string */ var floatValue: Float { return (self as NSString).floatValue } /** Subscript to allow for quick String substrings ["Hello"][0...1] = "He" */ subscript (r: Range) -> String { get { let start = self.startIndex.advancedBy(r.startIndex) let end = self.startIndex.advancedBy(r.endIndex - 1) return self.substringWithRange(start.. 

No hay conversión incorporada de una cadena hexadecimal a un UIColor (o CGColor ) que yo sepa. Sin embargo, puede escribir fácilmente un par de funciones para este fin, por ejemplo, ver el desarrollo de iphone accediendo a componentes uicolor

Puedes hacer una extensión como esta

 extension UIColor{ convenience init(rgb: UInt, alphaVal: CGFloat) { self.init( red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgb & 0x0000FF) / 255.0, alpha: alphaVal ) } } 

Y úsala en cualquier lugar como este

 UIColor(rgb: 0xffffff, alphaVal: 0.2) 

Encontré una buena categoría de UIColor para esto, UIColor + PXExtensions .

Uso: UIColor *mycolor = [UIColor pxColorWithHexValue:@"#BADA55"];

Y, en caso de que el enlace a mi idea principal falle, aquí está el código de implementación real:

 // // UIColor+PXExtensions.m // #import "UIColor+UIColor_PXExtensions.h" @implementation UIColor (UIColor_PXExtensions) + (UIColor*)pxColorWithHexValue:(NSString*)hexValue { //Default UIColor *defaultResult = [UIColor blackColor]; //Strip prefixed # hash if ([hexValue hasPrefix:@"#"] && [hexValue length] > 1) { hexValue = [hexValue substringFromIndex:1]; } //Determine if 3 or 6 digits NSUInteger componentLength = 0; if ([hexValue length] == 3) { componentLength = 1; } else if ([hexValue length] == 6) { componentLength = 2; } else { return defaultResult; } BOOL isValid = YES; CGFloat components[3]; //Seperate the R,G,B values for (NSUInteger i = 0; i < 3; i++) { NSString *component = [hexValue substringWithRange:NSMakeRange(componentLength * i, componentLength)]; if (componentLength == 1) { component = [component stringByAppendingString:component]; } NSScanner *scanner = [NSScanner scannerWithString:component]; unsigned int value; isValid &= [scanner scanHexInt:&value]; components[i] = (CGFloat)value / 256.0f; } if (!isValid) { return defaultResult; } return [UIColor colorWithRed:components[0] green:components[1] blue:components[2] alpha:1.0]; } @end 

Esta es otra alternativa.

 - (UIColor *)colorWithRGBHex:(UInt32)hex { int r = (hex >> 16) & 0xFF; int g = (hex >> 8) & 0xFF; int b = (hex) & 0xFF; return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1.0f]; } 

Puede usar varias herramientas en línea para convertir una cadena HEX en UIColor real. Echa un vistazo a uicolor.org o UI Color Picker . La salida se convertiría en código Objective-C, como:

 [UIColor colorWithRed:0.93 green:0.80 blue:0.80 alpha:1.0]; 

Que podría incrustar en su aplicación. ¡Espero que esto ayude!

versión rápida. Usar como una función o una extensión.

Función

  func UIColorFromRGB(colorCode: String, alpha: Float = 1.0) -> UIColor{ var scanner = NSScanner(string:colorCode) var color:UInt32 = 0; scanner.scanHexInt(&color) let mask = 0x000000FF let r = CGFloat(Float(Int(color >> 16) & mask)/255.0) let g = CGFloat(Float(Int(color >> 8) & mask)/255.0) let b = CGFloat(Float(Int(color) & mask)/255.0) return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha)) } 

Extensión

 extension UIColor { convenience init(colorCode: String, alpha: Float = 1.0){ var scanner = NSScanner(string:colorCode) var color:UInt32 = 0; scanner.scanHexInt(&color) let mask = 0x000000FF let r = CGFloat(Float(Int(color >> 16) & mask)/255.0) let g = CGFloat(Float(Int(color >> 8) & mask)/255.0) let b = CGFloat(Float(Int(color) & mask)/255.0) self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha)) } } 

Como llamar

 let hexColorFromFunction = UIColorFromRGB("F4C124", alpha: 1.0) let hexColorFromExtension = UIColor(colorCode: "F4C124", alpha: 1.0) 

También puede definir su Hex Color desde el constructor de interfaz.

enter image description here

Esto es bueno con el soporte de cocoapod

https://github.com/mRs-/HexColors

 // with hash NSColor *colorWithHex = [NSColor colorWithHexString:@"#ff8942" alpha:1]; // wihtout hash NSColor *secondColorWithHex = [NSColor colorWithHexString:@"ff8942" alpha:1]; // short handling NSColor *shortColorWithHex = [NSColor colorWithHexString:@"fff" alpha:1] 

Otra versión con alfa

 #define UIColorFromRGBA(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF000000) >> 24))/255.0 green:((float)((rgbValue & 0xFF0000) >> 16))/255.0 blue:((float)((rgbValue & 0xFF00) >> 8 ))/255.0 alpha:((float)((rgbValue & 0xFF))/255.0)] 

Swift equivalente a la respuesta de @ Tom, aunque recibe el valor RGBA Int para admitir la transparencia:

 func colorWithHex(aHex: UInt) -> UIColor { return UIColor(red: CGFloat((aHex & 0xFF000000) >> 24) / 255, green: CGFloat((aHex & 0x00FF0000) >> 16) / 255, blue: CGFloat((aHex & 0x0000FF00) >> 8) / 255, alpha: CGFloat((aHex & 0x000000FF) >> 0) / 255) } //usage var color = colorWithHex(0x7F00FFFF) 

Y si quieres poder utilizarlo desde una cadena, puedes usar strtoul:

 var hexString = "0x7F00FFFF" let num = strtoul(hexString, nil, 16) var colorFromString = colorWithHex(num) 

Otra implementación que permite cadenas como "FFF" o "FFFFFF" y que usa alfa:

 + (UIColor *) colorFromHexString:(NSString *)hexString alpha: (CGFloat)alpha{ NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""]; if([cleanString length] == 3) { cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@", [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)], [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)], [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]]; } if([cleanString length] == 6) { cleanString = [cleanString stringByAppendingString:@"ff"]; } unsigned int baseValue; [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue]; float red = ((baseValue >> 24) & 0xFF)/255.0f; float green = ((baseValue >> 16) & 0xFF)/255.0f; float blue = ((baseValue >> 8) & 0xFF)/255.0f; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } 

Aquí hay una versión de Swift 1.2 escrita como una extensión de UIColor . Esto te permite hacer

 let redColor = UIColor(hex: "#FF0000") 

Lo cual creo que es la forma más natural de hacerlo.

 extension UIColor { // Initialiser for strings of format '#_RED_GREEN_BLUE_' convenience init(hex: String) { let redRange = Range(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(3)) let greenRange = Range(start: hex.startIndex.advancedBy(3), end: hex.startIndex.advancedBy(5)) let blueRange = Range(start: hex.startIndex.advancedBy(5), end: hex.startIndex.advancedBy(7)) var red : UInt32 = 0 var green : UInt32 = 0 var blue : UInt32 = 0 NSScanner(string: hex.substringWithRange(redRange)).scanHexInt(&red) NSScanner(string: hex.substringWithRange(greenRange)).scanHexInt(&green) NSScanner(string: hex.substringWithRange(blueRange)).scanHexInt(&blue) self.init( red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: 1 ) } } 
  You Can Get UIColor From String Code Like circularSpinner.fillColor = [self getUIColorObjectFromHexString:@"27b8c8" alpha:9]; //Function For Hex Color Use - (unsigned int)intFromHexString:(NSString *)hexStr { unsigned int hexInt = 0; // Create scanner NSScanner *scanner = [NSScanner scannerWithString:hexStr]; // Tell scanner to skip the # character [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]]; // Scan hex value [scanner scanHexInt:&hexInt]; return hexInt; } - (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha { // Convert hex string to an integer unsigned int hexint = [self intFromHexString:hexStr]; // Create color object, specifying alpha as well UIColor *color = [UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255 green:((CGFloat) ((hexint & 0xFF00) >> 8))/255 blue:((CGFloat) (hexint & 0xFF))/255 alpha:alpha]; return color; } /Function For Hex Color Use - (unsigned int)intFromHexString:(NSString *)hexStr { unsigned int hexInt = 0; // Create scanner NSScanner *scanner = [NSScanner scannerWithString:hexStr]; // Tell scanner to skip the # character [scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]]; // Scan hex value [scanner scanHexInt:&hexInt]; return hexInt; } - (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha { // Convert hex string to an integer unsigned int hexint = [self intFromHexString:hexStr]; // Create color object, specifying alpha as well UIColor *color = [UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255 green:((CGFloat) ((hexint & 0xFF00) >> 8))/255 blue:((CGFloat) (hexint & 0xFF))/255 alpha:alpha]; return color; } 

actualizado para veloz 1.2

 class func colorWithHexString (hex:String) -> UIColor { var cString: NSString = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(1) } if (count(cString as String) != 6) { return UIColor.grayColor() } var rString: String = cString.substringToIndex(2) var gString: String = (cString.substringFromIndex(2) as NSString).substringToIndex(2) var bString: String = (cString.substringFromIndex(4) as NSString).substringToIndex(2) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; NSScanner(string: rString).scanHexInt(&r) NSScanner(string: gString).scanHexInt(&g) NSScanner(string: bString).scanHexInt(&b) return UIColor(red: CGFloat(Float(r) / 255.0), green: CGFloat(Float(g) / 255.0), blue: CGFloat(Float(b) / 255.0), alpha: CGFloat(1)) } 

Me gusta asegurar el alfa además del color, entonces escribo mi propia categoría

 + (UIColor *) colorWithHex:(int)color { float red = (color & 0xff000000) >> 24; float green = (color & 0x00ff0000) >> 16; float blue = (color & 0x0000ff00) >> 8; float alpha = (color & 0x000000ff); return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0]; } 

fácil de usar como este

 [UIColor colorWithHex:0xFF0000FF]; //Red [UIColor colorWithHex:0x00FF00FF]; //Green [UIColor colorWithHex:0x00FF00FF]; //Blue [UIColor colorWithHex:0x0000007F]; //transparent black 
 extension UIColor { convenience init(hexaString: String, alpha: CGFloat = 1) { let chars = Array(hexaString.characters) self.init(red: CGFloat(strtoul(String(chars[1...2]),nil,16))/255, green: CGFloat(strtoul(String(chars[3...4]),nil,16))/255, blue: CGFloat(strtoul(String(chars[5...6]),nil,16))/255, alpha: alpha)} } 

Uso:

 let redColor = UIColor(hexaString: "#FF0000") // r 1,0 g 0,0 b 0,0 a 1,0 let transparentRed = UIColor(hexaString: "#FF0000", alpha: 0.5) // r 1,0 g 0,0 b 0,0 a 0,5 

Crea una extensión elegante para UIColor :

 extension UIColor { convenience init(string: String) { var uppercasedString = string.uppercased() uppercasedString.remove(at: string.startIndex) var rgbValue: UInt32 = 0 Scanner(string: uppercasedString).scanHexInt32(&rgbValue) let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0 let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0 let blue = CGFloat(rgbValue & 0x0000FF) / 255.0 self.init(red: red, green: green, blue: blue, alpha: 1) } } 

Crear color rojo:

 let red = UIColor(string: "#ff0000") 
 extension UIColor { class func fromHexaString(hex:String) -> UIColor { let scanner = Scanner(string: hex) scanner.scanLocation = 0 var rgbValue: UInt64 = 0 scanner.scanHexInt64(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } //you can call like this. UIColor.fromHexaString(hex:3276b1) 

Terminé creando una categoría para UIColor que puedo reutilizar en mis otros proyectos. Github: https://github.com/mattquiros/UIColorHexColor

El uso es como:

 UIColor *customRedColor = [UIColor colorFromHex:0x990000]; 

Esto es mucho más rápido que pasar una cadena y convertirla a un número y luego cambiar los bits.

También puede importar la categoría desde su archivo .pch para que pueda usar colorFromHex en todas partes en su aplicación como si UIColor incorporada en UIColor :

 #ifdef __OBJC__ #import  #import  // Your other stuff here... #import "UIColor+HexColor.h" #endif 

Creé un init de conveniencia para eso:

 extension UIColor { convenience init(hex: String, alpha: CGFloat) { let redH = CGFloat(strtoul(hex.substringToIndex(advance(hex.startIndex,2)), nil, 16)) let greenH = CGFloat(strtoul(hex.substringWithRange(Range(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4))), nil, 16)) let blueH = CGFloat(strtoul(hex.substringFromIndex(advance(hex.startIndex,4)), nil, 16)) self.init(red: redH/255, green: greenH/255, blue: blueH/255, alpha: alpha) } } 

entonces puedes crear un UIColor en cualquier lugar de tu proyecto como este:

 UIColor(hex: "ffe3c8", alpha: 1) 

espero que esto ayude…

Puede crear una clase de extensión de UIColor como: –

extensión UIColor {

// MARK: – getColorFromHex / ** Esta función convertirá el código hexadecimal de color a RGB.

 - parameter color hex string. - returns: RGB color code. */ class func getColorFromHex(hexString:String)->UIColor{ var rgbValue : UInt32 = 0 let scanner:NSScanner = NSScanner(string: hexString) scanner.scanLocation = 1 scanner.scanHexInt(&rgbValue) return UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0)) } 

}

For swift 2.0+. This code works fine to me.

 extension UIColor { /// UIColor(hexString: "#cc0000") internal convenience init?(hexString:String) { guard hexString.characters[hexString.startIndex] == Character("#") else { return nil } guard hexString.characters.count == "#000000".characters.count else { return nil } let digits = hexString.substringFromIndex(hexString.startIndex.advancedBy(1)) guard Int(digits,radix:16) != nil else{ return nil } let red = digits.substringToIndex(digits.startIndex.advancedBy(2)) let green = digits.substringWithRange(Range(start: digits.startIndex.advancedBy(2), end: digits.startIndex.advancedBy(4))) let blue = digits.substringWithRange(Range(start:digits.startIndex.advancedBy(4), end:digits.startIndex.advancedBy(6))) let redf = CGFloat(Double(Int(red, radix:16)!) / 255.0) let greenf = CGFloat(Double(Int(green, radix:16)!) / 255.0) let bluef = CGFloat(Double(Int(blue, radix:16)!) / 255.0) self.init(red: redf, green: greenf, blue: bluef, alpha: CGFloat(1.0)) } } 

This code includes string format checking. p.ej

 let aColor = UIColor(hexString: "#dadada")! let failed = UIColor(hexString: "123zzzz") 

And as far as I know, my code is of no disadvantage for its maintaining the semantic of failible condition and returning an optional value. And this should be the best answer.

Swift 2.0 version of solution which will handle alpha value of color and with perfect error handling is here:

 func RGBColor(hexColorStr : String) -> UIColor?{ var red:CGFloat = 0.0 var green:CGFloat = 0.0 var blue:CGFloat = 0.0 var alpha:CGFloat = 1.0 if hexColorStr.hasPrefix("#"){ let index = hexColorStr.startIndex.advancedBy(1) let hex = hexColorStr.substringFromIndex(index) let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { if hex.characters.count == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if hex.characters.count == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("invalid hex code string, length should be 7 or 9", terminator: "") return nil } } else { print("scan hex error") return nil } } let color: UIColor = UIColor(red:CGFloat(red), green: CGFloat(green), blue:CGFloat(blue), alpha: alpha) return color } 

Puedes usar esta biblioteca

https://github.com/burhanuddin353/TFTColor

Rápido

 UIColor.colorWithRGB(hexString: "FF34AE" alpha: 1.0) 

C objective

 [UIColor colorWithRGBHexString:@"FF34AE" alpha:1.0f]