Swift4:十六进制字符串转UIColor

extension UIColor {
     static func hexStringToUIColor(hexString:String,alpha:CGFloat)->UIColor {
        print(hexString.count)
        let tmpstring = hexString.replacingOccurrences(of: "#", with: "")
        guard hexString.count != 6  else { return UIColor.clear }
        var tmpStr = tmpstring
        var i = 0
        var data = Data()
        for _ in 0..            let index = tmpStr.index((tmpStr.startIndex), offsetBy: 2)
            let str = String(tmpStr.prefix(upTo: index))
            tmpStr.removeSubrange(str.startIndex..            var result:UInt32 = 0
            Scanner(string: str).scanHexInt32(&result)
            data.append(UInt8(result))
            i = i+2
        }
        return UIColor.init(red: CGFloat(data[0])/255.0, green: CGFloat(data[1])/255.0, blue: CGFloat(data[2])/255.0, alpha: alpha)
    }
}

let color = UIColor.hexStringToUIColor(hexString: "#55A267", alpha: 1.0)

你可能感兴趣的:(Swift4:十六进制字符串转UIColor)