Skip to content

Instantly share code, notes, and snippets.

@iAmrSalman
Last active November 9, 2017 07:47
Show Gist options
  • Save iAmrSalman/4de6a1d8d24107947ac6cadc14f2849e to your computer and use it in GitHub Desktop.
Save iAmrSalman/4de6a1d8d24107947ac6cadc14f2849e to your computer and use it in GitHub Desktop.
[color from hex] #uicolor #extension
import UIKit
extension UIColor {
func colorFromHexString (_ hex:String, alpha: Float = 1.0) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.characters.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(alpha)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment