Skip to content

Instantly share code, notes, and snippets.

@mikeMTOL
Last active August 29, 2015 14:04
Show Gist options
  • Save mikeMTOL/c9c506c564fca768b490 to your computer and use it in GitHub Desktop.
Save mikeMTOL/c9c506c564fca768b490 to your computer and use it in GitHub Desktop.
UIColor extension and String substring extension
//
// Color+Utils.swift
// taskmanager
//
// Created by Mike on 2014-07-30.
// Copyright (c) 2014 Mike. All rights reserved.
//
import UIKit
extension String
{
subscript (i: Int) -> String {
return String(Array(self)[i])
}
subscript (r: Range<Int>) -> String {
var start = advance(startIndex, r.startIndex)
var end = advance(startIndex, r.endIndex)
return substringWithRange(Range(start: start, end: end))
}
}
extension UIColor {
convenience init(string:String) {
var scolor = string.stringByReplacingOccurrencesOfString("#", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
scolor = scolor.stringByReplacingOccurrencesOfString("0x", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
switch(countElements(scolor)) {
case 3:
let red = scolor[0]
let green = scolor[1]
let blue = scolor[2]
scolor = red+red + green+green + blue+blue + "ff"
case 6:
scolor = scolor + "ff"
case 8:
scolor = scolor + ""
// so compiler doesn't complain
default:
scolor = "00000000"
}
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0, a:CUnsignedInt = 0;
NSScanner.scannerWithString(scolor[0..<2]).scanHexInt(&r)
NSScanner.scannerWithString(scolor[2..<4]).scanHexInt(&g)
NSScanner.scannerWithString(scolor[4..<6]).scanHexInt(&b)
NSScanner.scannerWithString(scolor[6..<8]).scanHexInt(&a)
var red:CGFloat = 0.0
var green:CGFloat = 0.0
var blue:CGFloat = 0.0
var alpha:CGFloat = 0.0
if let x = String(r).toInt() {
red = CGFloat(x) / 255.0
}
if let x = String(g).toInt() {
green = CGFloat(x) / 255.0
}
if let x = String(b).toInt() {
blue = CGFloat(x) / 255.0
}
if let x = String(a).toInt() {
alpha = CGFloat(x) / 255.0
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment