欢迎来到代码驿站!

当前位置:首页 >

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

时间:2021-03-23 09:35:28|栏目:|点击:

本文环境

  • Xcode 12
  • Swift 5.3
  • iOS 13

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

使用 Extension 扩展

新建一个 swift 文件

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

//
// String.swift
// bestWhiteNoise
//
// Created by 袁超 on 2020/10/10.
//

import Foundation
import UIKit

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, 那么我们直接使用字符的扩展函数即可

"5188e1".uicolor()

如设置 TabBarItem 的字体颜色

item.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: "5188e1".uicolor()], for: .selected)

uicolor 函数也是在网上找到的,之前的函数在 iOS 13 中,scanHexInt34 方法被废弃,故此方法适配了 iOS 13

总结

上一篇:个人录制经常用到的Adobe Audition 3.0 完美者特别优化版

栏    目:

下一篇:Powershell小技巧之通过EventLog查看近期电脑开机和关机时间

本文标题:swift5.3 UIColor使用十六进制颜色的方法实例

本文地址:http://www.codeinn.net/misctech/86506.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有