Skip to content

Instantly share code, notes, and snippets.

@emajcher
Created June 28, 2016 03:53
Show Gist options
  • Save emajcher/99f3c8de48f1560d066e6a4bcdefac25 to your computer and use it in GitHub Desktop.
Save emajcher/99f3c8de48f1560d066e6a4bcdefac25 to your computer and use it in GitHub Desktop.
Create a UIColor from a hex string
//
// UIColor+Hex.swift
//
// Created by Edward Majcher on 6/27/16.
//
//
import Foundation
extension UIColor {
convenience init(hex: String) {
let rgb = UIColor.rgb(hex: hex)
self.init(red: rgb.red, green: rgb.green, blue: rgb.blue, alpha: 1.0)
}
static func rgb(hex hex:String) -> (red: CGFloat, green: CGFloat, blue: CGFloat) {
let scanner = NSScanner(string: hex)
var scanStart = 0
if let range = hex.rangeOfString("#") {
scanStart = hex.startIndex.distanceTo(range.startIndex) + 1
}
scanner.scanLocation = scanStart
var hexInt: UInt32 = 0
if !scanner.scanHexInt(&hexInt) {
return (red: 0, green: 0, blue: 0)
}
let red = CGFloat((hexInt & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hexInt & 0xFF00) >> 8) / 255.0
let blue = CGFloat(hexInt & 0xFF) / 255.0
return (red, green, blue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment