Swift3.0中十六进制颜色转换UIColor

第一种方式是给String添加扩展

extension String {
    /// 将十六进制颜色转换为UIColor
    func uiColor() -> UIColor {
        // 存储转换后的数值
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        // 分别转换进行转换
        Scanner(string: self[0..<2]).scanHexInt32(&red)

        Scanner(string: self[2..<4]).scanHexInt32(&green)

        Scanner(string: self[4..<6]).scanHexInt32(&blue)

        return UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
    }

}

第二种方式是给UIColor添加扩展

import UIKit

extension UIColor {

    /// 用十六进制颜色创建UIColor
    ///
    /// - Parameter hexColor: 十六进制颜色 (0F0F0F)
    convenience init(hexColor: String) {

        // 存储转换后的数值
        var red:UInt32 = 0, green:UInt32 = 0, blue:UInt32 = 0

        // 分别转换进行转换
        Scanner(string: hexColor[0..<2]).scanHexInt32(&red)

        Scanner(string: hexColor[2..<4]).scanHexInt32(&green)

        Scanner(string: hexColor[4..<6]).scanHexInt32(&blue)

        self.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1.0)
    }
}

两种方式都需要用到的扩展

extension String {

    /// String使用下标截取字符串
    /// 例: "示例字符串"[0..<2] 结果是 "示例"
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)

            return self[startIndex..<endIndex]
        }
    }
}

你可能感兴趣的:(swift开发随笔)