Skip to content

Instantly share code, notes, and snippets.

@chajka
Last active August 8, 2018 17:27
Show Gist options
  • Save chajka/d7df8019ebc20c6e9bcee552cad503fd to your computer and use it in GitHub Desktop.
Save chajka/d7df8019ebc20c6e9bcee552cad503fd to your computer and use it in GitHub Desktop.
HexColor and NSColor byway value transformer
//
// HexAndNSColorTransformer.swift
// Charleston
//
// Created by Чайка on 2018/08/08.
// Copyright © 2018 Чайка. All rights reserved.
//
import Cocoa
class HexAndNSColorTransformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSString.self
}// end class func transformedValueClass
override class func allowsReverseTransformation() -> Bool {
return true
}// end class func allowsReverseTransformation
override func transformedValue(_ value: Any?) -> Any? {
guard let color: NSColor = value as? NSColor else { return "#ffffff" }
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 0.0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
let hexColor: NSMutableString = NSMutableString(string: "#")
[red, green, blue].forEach { (elem) in
let element: String = String(format: "%02d", (elem * CGFloat(0xff)))
hexColor.append(element)
}// end foreach color element
if alpha != 0.0 {
let a: String = String(format: "%02d", (alpha * CGFloat(0xff)))
hexColor.append(a)
}// end if color have alpha element
return hexColor
}// end transformedValue
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let hexColor: NSString = value as? NSString else { return NSColor.white }
guard hexColor.substring(with: NSMakeRange(0, 1)) == "#" else { return NSColor.white }
let len: Int = hexColor.length
if len == 7 || len == 9 {
var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
let hexRed: String = hexColor.substring(with: NSMakeRange(1, 2))
red = CGFloat(UInt(hexRed, radix: 16) ?? 0) / CGFloat(0xff)
let hexGreen: String = hexColor.substring(with: NSMakeRange(3, 2))
green = CGFloat(UInt(hexGreen, radix: 16) ?? 0) / CGFloat(0xff)
let hexBlue: String = hexColor.substring(with: NSMakeRange(5, 2))
blue = CGFloat(UInt(hexBlue, radix: 16) ?? 0) / CGFloat(0xff)
if len == 9 {
let hexAlpha: String = hexColor.substring(with: NSMakeRange(7, 2))
alpha = CGFloat(UInt(hexAlpha, radix: 16) ?? 0) / CGFloat(0xff)
}// end if string
return NSColor(calibratedRed: red, green: green, blue: blue, alpha: alpha)
} else {
return NSColor.white
}// end if much length
}// end reverseTransformedValue
}// end class HexAndNSColorTransformer
extension NSValueTransformerName {
static let HexAndNSColorTransformerName = NSValueTransformerName(rawValue: "HexAndNSColorTransformer")
}// end extension NSValueTransformerName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment