本文环境

  • Xcode 12
  • Swift 5.3
  • iOS 13

UI 给出的色彩往往都是十六进制的,如 #1a1a1a 等,然而咱们在 iOS中是不能间接应用的,查问了一些代码,发现比拟老旧,这里给出一个改良版本

应用 Extension 扩大

新建一个 swift 文件

比方我的 string.swift ,复制以下代码

////  String.swift//  bestWhiteNoise////  Created by 袁超 on 2020/10/10.//import Foundationimport UIKitextension 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, 那么咱们间接应用字符的扩大函数即可

"5188e1".uicolor()

如设置 TabBarItem 的字体色彩

item.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: "5188e1".uicolor()], for: .selected)
uicolor 函数也是在网上找到的,之前的函数在 iOS 13 中,scanHexInt34 办法被废除,故此办法适配了 iOS 13