如何将字符串中的标准颜色名称转换为UIColor值

问题描述 投票:0回答:1

我有一个变量:

var colorName = String()

我需要将按钮的色调颜色设置为适当的颜色。执行以下操作:

cell.btn.tintColor = UIColor.red 

为我工作。但是我需要使用我的colorName变量而不是“ UIColor.red”表达式。

如何将字符串UIColor初始化为redUIColor.red

ios swift string colors uicolor
1个回答
0
投票

[没有内置功能可以使UIColor具有名称。您可以编写一个扩展名,类似于Paul Hudson的扩展名:https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-html-name-string-into-a-uicolor

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

        if hexString.hasPrefix("#") {
            let start = hexString.index(hexString.startIndex, offsetBy: 1)
            let hexColor = hexString.substring(from: 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
    }

    public convenience init?(name: String) {
        let allColors = [
            "red": "#FF0000FF",
        ]

        let cleanedName = name.replacingOccurrences(of: " ", with: "").lowercased()

        if let hexString = allColors[cleanedName] {
            self.init(hexString: hexString)
        } else {
            return nil
        }
    }
}

然后使用它:

let redColor = UIColor(name: "red")
© www.soinside.com 2019 - 2024. All rights reserved.