我试图在Swift中使用十六进制颜色值,而不是UIColor允许您使用的少数标准值,但我不知道如何做到这一点。

示例:我如何使用#ffffff作为颜色?


当前回答

斯威夫特5.0

你不能在Swift中直接使用#ffffff语法。以下是我用于网络相关项目的代码。支持alpha和三位数字。

用法示例(大写值也可以):

    let hex = "#FADE2B"  // yellow
    let color = NSColor(fromHex: hex)

支持的字符串格式:

"fff" // RGB "#fff" // #RGB "ffff" // RGBA "#ffff" // #RGBA . "ffffff" // RRGGBB . "#ffffff" // #RRGGBB . "ffffffff" // RRGGBBAA . "#ffffffff" // #RRGGBBAA .

数字代表红色,绿色,蓝色和阿尔法(像透明度)。对于iOS,用UIColor替换NSColor。

代码:


    extension NSColor {
        /// Initialises NSColor from a hexadecimal string. Color is clear if string is invalid.
        /// - Parameter fromHex: supported formats are "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA", with or without the # character
        public convenience init(fromHex:String) {
            var r = 0, g = 0, b = 0, a = 255
            let offset = fromHex.hasPrefix("#") ? 1 : 0
            let ch = fromHex.map{$0}
            switch(ch.count - offset) {
            case 8:
                a = 16 * (ch[offset+6].hexDigitValue ?? 0) + (ch[offset+7].hexDigitValue ?? 0)
                fallthrough
            case 6:
                r = 16 * (ch[offset+0].hexDigitValue ?? 0) + (ch[offset+1].hexDigitValue ?? 0)
                g = 16 * (ch[offset+2].hexDigitValue ?? 0) + (ch[offset+3].hexDigitValue ?? 0)
                b = 16 * (ch[offset+4].hexDigitValue ?? 0) + (ch[offset+5].hexDigitValue ?? 0)
                break
            case 4:
                a = 16 * (ch[offset+3].hexDigitValue ?? 0) + (ch[offset+3].hexDigitValue ?? 0)
                fallthrough
            case 3:  // Three digit #0D3 is the same as six digit #00DD33
                r = 16 * (ch[offset+0].hexDigitValue ?? 0) + (ch[offset+0].hexDigitValue ?? 0)
                g = 16 * (ch[offset+1].hexDigitValue ?? 0) + (ch[offset+1].hexDigitValue ?? 0)
                b = 16 * (ch[offset+2].hexDigitValue ?? 0) + (ch[offset+2].hexDigitValue ?? 0)
                break
            default:
                a = 0
                break
            }
            self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
            
        }
    }
    // Author: Andrew Kingdom

授权:CC BY

我发现这比下面的复制/粘贴更整洁

选择:

您可以删除#并将其存储为32位无符号整数字面量,由0x前缀表示,即0xffffff。不过,你仍然需要代码将其转换为颜色。

如果你想要一种非编程的方式来获取颜色:打开一个颜色选择器对话框,切换到colour Sliders > RGB Sliders,并将值粘贴/输入到“Hex color #”框中。(不要粘贴#散列符号。)

其他回答

在Swift 2.0和Xcode 7.0.1中,你可以创建这个函数:

    // Creates a UIColor from a Hex string.
    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))
    }

然后这样使用它:

let color1 = colorWithHexString("#1F437C")

Swift 4更新

func colorWithHexString (hex:String) -> UIColor {

    var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString = (cString as NSString).substring(from: 1)
    }

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

    let rString = (cString as NSString).substring(to: 2)
    let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
    let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)

    var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
    Scanner(string: rString).scanHexInt32(&r)
    Scanner(string: gString).scanHexInt32(&g)
    Scanner(string: bString).scanHexInt32(&b)


    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}

这是一个接受十六进制字符串并返回UIColor的函数。 (你可以输入十六进制字符串格式:#ffffff或ffffff)

用法:

var color1 = hexStringToUIColor("#d3d3d3")

Swift 5:(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:UInt64 = 0
    Scanner(string: cString).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)
    )
}

斯威夫特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)
    )
}

斯威夫特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)
    )
}


沙德源代码:/ gist: de147c42d7b3063ef7bc

编辑:更新代码。谢谢,Hlung, jaytrixz, Ahmad F, Kegham K和Adam Waite!

支持7十六进制颜色类型

有7种十六进制颜色格式:""#FF0000","0xFF0000", "FF0000", "F00", "red", 0x00FF00, 16711935

NSColorParser.nsColor("#FF0000",1)//red nsColor
NSColorParser.nsColor("FF0",1)//red nsColor
NSColorParser.nsColor("0xFF0000",1)//red nsColor
NSColorParser.nsColor("#FF0000",1)//red nsColor
NSColorParser.nsColor("FF0000",1)//red nsColor
NSColorParser.nsColor(0xFF0000,1)//red nsColor
NSColorParser.nsColor(16711935,1)//red nsColor

注意:这不是一个“单文件解决方案”,有一些依赖关系,但查找它们可能比从头开始研究更快。

https://github.com/eonist/swift-utils/blob/2882002682c4d2a3dc7cb3045c45f66ed59d566d/geom/color/NSColorParser.swift

永久链接: https://github.com/eonist/Element/wiki/Progress#supporting-7-hex-color-types

我做了一个小函数,把它放在我可以全局使用它的地方,在swift 2.1中工作得很好:

func getColorFromHex(rgbValue:UInt32)->UIColor{
   let red = CGFloat((rgbValue & 0xFF0000) >> 16)/255.0
   let green = CGFloat((rgbValue & 0xFF00) >> 8)/255.0
   let blue = CGFloat(rgbValue & 0xFF)/255.0

   return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}

用法:

getColorFromHex(0xffffff)

以编程方式添加颜色的最简单方法是使用ColorLiteral。

只要像例子中那样添加ColorLiteral属性,Xcode就会提示你一个你可以选择的颜色列表。这样做的好处是代码更少,添加HEX值或RGB。您还将从故事板中获得最近使用的颜色。

例子: self.view.backgroundColor = ColorLiteral