欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

swift5.3 UIColor使用十六進(jìn)制顏色的方法實(shí)例

 更新時(shí)間:2020年10月15日 09:53:54   作者:enda  
這篇文章主要給大家介紹了關(guān)于swift5.3 UIColor使用十六進(jìn)制顏色的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

本文環(huán)境

  • Xcode 12
  • Swift 5.3
  • iOS 13

UI 給出的顏色往往都是十六進(jìn)制的,如 #1a1a1a 等,但是我們?cè)?iOS中是不能直接使用的,查詢了一些代碼,發(fā)現(xiàn)比較老舊,這里給出一個(gè)改進(jìn)版本

使用 Extension 擴(kuò)展

新建一個(gè) swift 文件

比如我的 string.swift ,復(fù)制以下代碼

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

import Foundation
import UIKit

extension String {
 /// 十六進(jìn)制字符串顏色轉(zhuǎn)為UIColor
 /// - Parameter alpha: 透明度
 func uicolor(alpha: CGFloat = 1.0) -> UIColor {
  // 存儲(chǔ)轉(zhuǎn)換后的數(shù)值
  var red: UInt64 = 0, green: UInt64 = 0, blue: UInt64 = 0
  var hex = self
  // 如果傳入的十六進(jìn)制顏色有前綴,去掉前綴
  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)...])
  }
  // 如果傳入的字符數(shù)量不足6位按照后邊都為0處理,當(dāng)然你也可以進(jìn)行其它操作
  if hex.count < 6 {
   for _ in 0..<6-hex.count {
    hex += "0"
   }
  }

  // 分別進(jìn)行轉(zhuǎn)換
  // 紅
  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)
  // 藍(lán)
  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, 那么我們直接使用字符的擴(kuò)展函數(shù)即可

"5188e1".uicolor()

如設(shè)置 TabBarItem 的字體顏色

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

uicolor 函數(shù)也是在網(wǎng)上找到的,之前的函數(shù)在 iOS 13 中,scanHexInt34 方法被廢棄,故此方法適配了 iOS 13

總結(jié)

到此這篇關(guān)于swift5.3 UIColor使用十六進(jìn)制顏色的文章就介紹到這了,更多相關(guān)swift5.3 UIColor用十六進(jìn)制顏色內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論