1.不废话,直接上代码
extension UIColor {
convenience init(hexString: String) {
var hexFormatted = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
if hexFormatted.hasPrefix("#") {
hexFormatted = String(hexFormatted.dropFirst())
}
assert(hexFormatted.count == 6, "Invalid hex code used.")
var rgbValue: UInt64 = 0
Scanner(string: hexFormatted).scanHexInt64(&rgbValue)
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: 1.0)
}
}
2.使用方法
override func viewDidLoad() {
super.viewDidLoad()
let view1 = UIView.init(frame: CGRect.init(x: 100, y:200 , width: 100, height: 50))
view1.backgroundColor = UIColor.init(hexString: "#00D8A0")
view.addSubview(view1)
}