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")
网友评论