Skip to content

Instantly share code, notes, and snippets.

@scottdelly
Created July 26, 2016 21:38
Show Gist options
  • Save scottdelly/1d06b278d7d1a12643466a6f2e64e8d2 to your computer and use it in GitHub Desktop.
Save scottdelly/1d06b278d7d1a12643466a6f2e64e8d2 to your computer and use it in GitHub Desktop.
A utility method to create a UIColor from an arbitrary string. Inspired by http://stackoverflow.com/a/16348977/2138077
func fromString(string: String) -> UIColor {
var hash = 0
let utf16array = Array(string.utf16)
for i in 0..<utf16array.count {
hash = Int(utf16array[i]) + ((hash << 5) - hash)
}
var colorValues = [CGFloat]()
for i in 0..<3 {
let value = (hash >> (i * 8)) & 0xFF
colorValues.append((CGFloat(value)/255.0))
}
return UIColor(red: colorValues[0], green: colorValues[1], blue: colorValues[2], alpha: 1)
}
@scottdelly
Copy link
Author

fromString("greenish")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment