美文网首页
Swift3.0 HexColor转UIColor

Swift3.0 HexColor转UIColor

作者: Bager | 来源:发表于2017-04-26 13:31 被阅读44次

extension UIColor{

classfunchex(hex:String) ->UIColor{

varcolorString = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased()

if(colorString.hasPrefix("#")) {

letindex = colorString.index(colorString.startIndex, offsetBy:1)

colorString = colorString.substring(from: index)

}

if(colorString.characters.count!=6) {

returnUIColor.red

}

letredIndex = colorString.index(colorString.startIndex, offsetBy:2)

letredString = colorString.substring(to: redIndex)

letotherString = colorString.substring(from: redIndex)

letgreenIndex = otherString.index(otherString.startIndex, offsetBy:2)

letgreenString = otherString.substring(to: greenIndex)

letblueIndex = colorString.index(colorString.endIndex, offsetBy:-2)

letblueString = colorString.substring(from: blueIndex)

varred:CUnsignedInt=0, green:CUnsignedInt=0, blue:CUnsignedInt=0;

Scanner(string: redString).scanHexInt32(&red)

Scanner(string: greenString).scanHexInt32(&green)

Scanner(string: blueString).scanHexInt32(&blue)

returnUIColor(red:CGFloat(red) /255.0, green:CGFloat(green) /255.0, blue:CGFloat(blue) /255.0, alpha:CGFloat(1))

}

}

Demo:

lethexColor =UIColor.hex(hex:"#FFFFFF")

相关文章

网友评论

      本文标题:Swift3.0 HexColor转UIColor

      本文链接:https://www.haomeiwen.com/subject/mhuizttx.html