Skip to content

Instantly share code, notes, and snippets.

@vadimsmirnovnsk
Last active September 27, 2015 08:09
Show Gist options
  • Save vadimsmirnovnsk/60284a934899b1630d6e to your computer and use it in GitHub Desktop.
Save vadimsmirnovnsk/60284a934899b1630d6e to your computer and use it in GitHub Desktop.
Swift Category for your custom UIColors
import UIKit
extension UIColor
{
struct dgs
{
static let edwardColor: UIColor =
{
return UIColor.colorWithHexString("#B1B3B3")!
}()
}
// MARK: - Private
class private func colorWithHexString(hexString:String) -> UIColor?
{
return UIColor.colorWithHex(UIColor.hexForHexString(hexString)!)
}
class private func colorWithHex(hex:UInt32) -> UIColor
{
return UIColor(red: CGFloat((hex & 0xFF0000) >> 16) / 255,
green: CGFloat((hex & 0xFF00) >> 8) / 255,
blue: CGFloat(hex & 0xFF) / 255,
alpha: CGFloat(1.0))
}
class private func hexForHexString(hexString:String) -> UInt32?
{
let unexpectedHexStringLength: Bool = (hexString.characters.count < 6) || (hexString.characters.count > 8)
if unexpectedHexStringLength
{
assert(false, "Invalid hex format")
return 0
}
let scanner: NSScanner = NSScanner(string: hexString)
scanner.scanLocation = (hexString.characters.first == "#") ? 1 : 0
var hex: UInt32 = 0
if !scanner.scanHexInt(&hex)
{
assert(false, "Invalid Hex Format")
return 0
}
return hex
}
}
@vadimsmirnovnsk
Copy link
Author

Description

Swift extension for the UIColor for adding your custom colors to application.
Every custom color will be lazy initialized just once.

Using

1. Just add your new color to struct dgs like here:

struct dgs
    {
        static let edwardColor: UIColor =
        {
            return UIColor.colorWithHexString("#B1B3B3")!
        }()

        static let yourNewColor: UIColor =
        {
            return UIColor.colorWithHexString("#??????")!
        }()
    }

2. Obtain your color anywhere in your code by calling, for example:

self.view.backgroundColor = UIColor.dgs.yourNewColor

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