swift5.3 UIColor使用十六进制颜色的方法实例

时间:2021-05-19

本文环境

  • 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

总结

到此这篇关于swift5.3 UIColor使用十六进制颜色的文章就介绍到这了,更多相关swift5.3 UIColor用十六进制颜色内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章