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

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


当前回答

extension UIColor {
    public convenience init?(hex: String) {
        let r, g, b, a: CGFloat

        if hex.hasPrefix("#") {
            let start = hex.index(hex.startIndex, offsetBy: 1)
            let hexColor = String(hex[start...])

            if hexColor.count == 8 {
                let scanner = Scanner(string: hexColor)
                var hexNumber: UInt64 = 0

                if scanner.scanHexInt64(&hexNumber) {
                    r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                    g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                    b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                    a = CGFloat(hexNumber & 0x000000ff) / 255

                    self.init(red: r, green: g, blue: b, alpha: a)
                    return
                }
            }
        }

        return nil
    }
}

用法:

let white = UIColor(hex: "#ffffff")

其他回答

斯威夫特4.0

使用这种单行方法

override func viewDidLoad() {
    super.viewDidLoad()

   let color = UIColor(hexColor: "FF00A0")
   self.view.backgroundColor = color

}

你必须创建新的类或使用任何控制器,你需要使用十六进制颜色。这个扩展类为您提供UIColor,将十六进制转换为RGB颜色。

extension UIColor {
convenience init(hexColor: String) {
    let scannHex = Scanner(string: hexColor)
    var rgbValue: UInt64 = 0
    scannHex.scanLocation = 0
    scannHex.scanHexInt64(&rgbValue)
    let r = (rgbValue & 0xff0000) >> 16
    let g = (rgbValue & 0xff00) >> 8
    let b = rgbValue & 0xff
    self.init(
        red: CGFloat(r) / 0xff,
        green: CGFloat(g) / 0xff,
        blue: CGFloat(b) / 0xff, alpha: 1
    )
  }
}

斯威夫特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 #”框中。(不要粘贴#散列符号。)

斯威夫特2.0:

做一个UIColor的扩展。

extension UIColor {
    convenience init(hexString:String) {
        let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        let scanner            = NSScanner(string: hexString as String)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }

        var color:UInt32 = 0
        scanner.scanHexInt(&color)

        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask

        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:1)
    }

    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return NSString(format:"#%06x", rgb) as String
    }

}

用法:

//Hex to Color
    let countPartColor =  UIColor(hexString: "E43038")

//Color to Hex
let colorHexString =  UIColor(red: 228, green: 48, blue: 56, alpha: 1.0).toHexString()

Swift 5:你可以在Xcode中创建颜色,如下图所示:

您应该命名颜色,因为您通过名称引用了颜色。如图2所示:

Xcode 13.2.1, M1, Swift 5.5

我们可以在ColorLiterals中使用Hex

输入#colorLiteral(在Xcode中,这将触发并修复与ColorLiterals相关的错误

然后点击其他

然后选择RGB滑块,你现在可以看到十六进制面板