Justin Duke

Sorting by UIColor

New in Barback 3.1 is the ability to sort ingredients just as you can sort recipes. One of the possible methods to sort by is the color of the ingredient, which is admittedly more of an aesthetic option than a functional one:

Sorting by UIColor in this manner — getting a bit of a rainbow effect — is actually fairly easy to pull off!

The trick is to use the semi-hidden (and, in Swift, semi-ugly) getHue function (listed in the Apple docs here).

getHue lets you retrieve the HSB 1 components from a given UIColor and store them in pointers that you provide to the function. Our key here is the hue specifically, since its the one that forms the rainbow gradient. Below is a mapping of hue values across a spectrum:

So all we need to do is compare two UIColors by their hues, which makes for a fairly simple comparator:

let firstColor = UIColor.redColor
let secondColor = UIColor.blueColor

// The actual values we end up comparing.
var firstHue: CGFloat = 0
var secondHue: CGFloat = 0

// Dummy pointers.
var saturation: CGFloat = 0
var brightness: CGFloat = 0
var alpha: CGFloat = 0
firstColor.getHue(&firstHue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
secondColor.getHue(&secondHue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
print(oneHue > twoHue)

You can also check it out how Barback does it, within a specific enum of different ingredient comparators:

    case .ColorAscending:
        return ({
            var oneHue: CGFloat = 0
            var twoHue: CGFloat = 0
            var saturation: CGFloat = 0
            var brightness: CGFloat = 0
            var alpha: CGFloat = 0
            $0.uiColor.getHue(&oneHue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
            $1.uiColor.getHue(&twoHue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
            return oneHue > twoHue

  1. Hue, saturation, brightness. [return]
Liked this post? You should subscribe to my newsletter and follow me on Twitter.

(I've got an RSS feed, too, if you'd prefer.)