我如何从十六进制字符串格式创建一个UIColor,如#00FF00?


当前回答

斯威夫特2.0:

将此方法添加到VC或扩展UIColor。

func colorWithHexString (hex:String) -> UIColor {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substringFromIndex(1)
        }

        if (cString.characters.count != 6) {
            return UIColor.grayColor()
        }

        let rString = (cString as NSString).substringToIndex(2)
        let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
        let bString = ((cString as NSString).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(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }

用法:

    loginButton.tintColor = self.colorWithHexString("#be1337")

     OR

    let hexColor = self.colorWithHexString("#be1337")

其他回答

Xamarin的。iOS你可以使用下面的宏来代替宏:

public UIColor UIColorFromHexValue(int value, float alpha = 1f) =>
    UIColor.FromRGBA(
        ((value & 0xFF0000) >> 16) / 255.0f,
        ((value & 0x00FF00) >> 16) / 255.0f,
        ((value & 0x0000FF) >> 16) / 255.0f,
        alpha);

用法类似:

label.TextColor = UIColorFromHexValue(0xBC1128);

斯威夫特4

你可以像这样在扩展中创建一个非常方便的构造函数:

extension UIColor {
    convenience init(hexString: String, alpha: CGFloat = 1.0) {
        var hexInt: UInt32 = 0
        let scanner = Scanner(string: hexString)
        scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
        scanner.scanHexInt32(&hexInt)

        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

        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
}

以后再用

let color = UIColor(hexString: "#AABBCCDD")
    //UIColorWithHexString

    static UIColor * UIColorWithHexString(NSString *hex) {
        unsigned int rgb = 0;
        [[NSScanner scannerWithString:
          [[hex uppercaseString] stringByTrimmingCharactersInSet:
           [[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"] invertedSet]]]
         scanHexInt:&rgb];
        return [UIColor colorWithRed:((CGFloat)((rgb & 0xFF0000) >> 16)) / 255.0
                               green:((CGFloat)((rgb & 0xFF00) >> 8)) / 255.0
                                blue:((CGFloat)(rgb & 0xFF)) / 255.0
                               alpha:1.0];
    }

使用

self.view.backgroundColor = UIColorWithHexString(@"#0F35C0");

您可以使用各种在线工具将HEX字符串转换为实际的UIColor。查看uicolor.org或UI颜色选择器。输出将被转换为Objective-C代码,如下所示:

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

可以嵌入到应用程序中。希望这能有所帮助!

下面是Swift 1.2版本,作为UIColor的扩展。这允许你这样做

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

我觉得这是最自然的做法。

extension UIColor {
  // Initialiser for strings of format '#_RED_GREEN_BLUE_'
  convenience init(hex: String) {
    let redRange    = Range<String.Index>(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(3))
    let greenRange  = Range<String.Index>(start: hex.startIndex.advancedBy(3), end: hex.startIndex.advancedBy(5))
    let blueRange   = Range<String.Index>(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
    )
  }
}