How can I create a UIColor from a hex string in swift?
Hi, Normally default color of the UIColor can easily set Like UIColor.redColor(). but you want to customize color, UIcolor class have RGB method to customize color Like UIColor(red: 222.0/255.0 , green: 222.0/255.0 , blue : 222.0/255.0 , alpha: 1.0). its also easy. but you have HEX code, there isn't any method to get color from HEX. here make one extension for UIColor to get color from HEX code.
extension of UIColor
extension UIColor{
func HexToColor(hexString: String, alpha:CGFloat? = 1.0) -> UIColor {
// Convert hex string to an integer
let hexint = Int(self.intFromHexString(hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
let alpha = alpha!
// Create color object, specifying alpha as well
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
// Create scanner
let scanner: NSScanner = NSScanner(string: hexStr)
// Tell scanner to skip the # character
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#")
// Scan hex value
scanner.scanHexInt(&hexInt)
return hexInt
}
}
How to use:self.view.backgroundColor = UIColor().HexToColor("#aa0e8b", alpha: 1.0)
HEX-Color-CODE LIST
Thanks.
How can I create a UIColor from a hex string in swift?
Reviewed by KIRIT MODI
on
23:56:00
Rating:
No comments: