美文网首页
Swift UIColor 使用十六进制颜色

Swift UIColor 使用十六进制颜色

作者: JianLee | 来源:发表于2021-06-24 17:42 被阅读0次

UI 给出的颜色往往都是十六进制的,如 #1a1a1a 等,但是我们在 iOS中是不能直接使用的,查询了一些代码,发现比较老旧,这里给出一个改进版本

使用 Extension 扩展

比如我的扩展函数uicolor

extension String {
    /// 十六进制字符串颜色转为UIColor
    /// - Parameter alpha: 透明度
    func uicolor(alpha: CGFloat = 1.0) -> UIColor {
        // 存储转换后的数值
        var red: UInt64 = 0, green: UInt64 = 0, blue: UInt64 = 0
        var hex = self
        // 如果传入的十六进制颜色有前缀,去掉前缀
        if hex.hasPrefix("0x") || hex.hasPrefix("0X") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 2)...])
        } else if hex.hasPrefix("#") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 1)...])
        }
        // 如果传入的字符数量不足6位按照后边都为0处理,当然你也可以进行其它操作
        if hex.count < 6 {
            for _ in 0..<6-hex.count {
                hex += "0"
            }
        }

        // 分别进行转换
        // 红
        Scanner(string: String(hex[..<hex.index(hex.startIndex, offsetBy: 2)])).scanHexInt64(&red)
        // 绿
        Scanner(string: String(hex[hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4)])).scanHexInt64(&green)
        // 蓝
        Scanner(string: String(hex[hex.index(startIndex, offsetBy: 4)...])).scanHexInt64(&blue)

        return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: alpha)
    }
}

使用

比如 UI 给的颜色是 #5188e1, 那么我们直接使用字符的扩展函数即可

        let mLabel = UILabel(frame: CGRect(x: 95, y: 120, width: 200, height: 40))
        mLabel.text="我是文本"
        mLabel.textColor="#189659".uicolor()
        mLabel.textAlignment=NSTextAlignment.center
        mLabel.minimumScaleFactor=0.5
        mLabel.adjustsFontSizeToFitWidth=true
        mLabel.layer.borderColor="#1A1A1A".uicolor().cgColor
        mLabel.layer.borderWidth = 5
        mLabel.layer.cornerRadius=10
        view.addSubview(mLabel)
image.png

相关文章

网友评论

      本文标题:Swift UIColor 使用十六进制颜色

      本文链接:https://www.haomeiwen.com/subject/twkgyltx.html