swift—UIColor十六进制

Posted st646889325

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift—UIColor十六进制相关的知识,希望对你有一定的参考价值。

  1. 新建一个文件UIColor+hex.swift

2.代码

import Foundation
import UIKit

extension UIColor
    
    class func colorWithHex(hexStr:String) -> UIColor
        return UIColor.colorWithHex(hexStr : hexStr, alpha:1)
    
    
    class func colorWithHex(hexStr:String, alpha:Float) -> UIColor
        
        var cStr = hexStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString;
        
        if(cStr.length < 6)
            return UIColor.clear;
        
        
        if(cStr.hasPrefix("0x"))
            cStr = cStr.substring(from: 2) as NSString
        
        
        if(cStr.hasPrefix("#"))
            cStr = cStr.substring(from: 1) as NSString
        
        
        if(cStr.length != 6)
            return UIColor.clear
        
        
        let rStr = (cStr as NSString).substring(to: 2)
        let gStr = ((cStr as NSString).substring(from: 2) as NSString).substring(to: 2)
        let bStr = ((cStr as NSString).substring(from: 4) as NSString).substring(to: 2)
        
        var r: UInt32 = 0x0
        var g: UInt32 = 0x0
        var b: UInt32 = 0x0
        
        Scanner.init(string: rStr).scanHexInt32(&r)
        Scanner.init(string: gStr).scanHexInt32(&g)
        Scanner.init(string: bStr).scanHexInt32(&b)
        
        return UIColor.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(alpha));
        
    


  1. 调用
 UIColor.colorWithHex(hexStr: "#e36464")
  UIColor.colorWithHex(hexStr: "#e36464",alpha:1)

以上是关于swift—UIColor十六进制的主要内容,如果未能解决你的问题,请参考以下文章

swift—UIColor十六进制

swift 十六进制颜色到UIColor

swift UIColor十六进制实用程序

swift 将十六进制字符串转换为UIColor

如何在 Swift 中创建十六进制颜色字符串 UIColor 初始化程序? [复制]

swift - label 的font 设置 文字字体和大小