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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

enda   2021-03-15 我要评论
想了解swift5.3 UIColor使用十六进制颜色的方法实例的相关内容吗,enda在本文为您仔细讲解swift5.3 UIColor用十六进制颜色的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:swift5.3,uicolor,swift,进制颜色,下面大家一起来学习吧。

本文环境

  • 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

总结

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们