paint-brush
Swifty UIColorsby@HaydenHolligan
749 reads
749 reads

Swifty UIColors

by Hayden HolliganJuly 25th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Custom <a href="https://hackernoon.com/tagged/swift" target="_blank">Swift</a> UIColors
featured image - Swifty UIColors
Hayden Holligan HackerNoon profile picture

Custom Swift UIColors

Back in Swift 2, or even earlier, UIColors were class functions, called via UIColor.blackColor() , UIColor.redColor() , etc.

Naturally, creating a custom colour would look something like

extension UIColor {

class func facebookBlue() -> UIColor {

return UIColor(red: 59/255, green: 89/255, blue: 152/255, alpha: 1)

}

and would be called via UIColor.facebookBlue() .

In Swift 3, default UIColors were modified to be class properties, called via UIColor.blue (or, if the type is already determined, simply .blue )

I’ve noticed a lot of people (myself included) are still creating custom UIColors the pre-Swift 3 way. But I ask, why would you, when you can write them like so:

extension UIColor {

class var facebookBlue: UIColor {

return UIColor(red: 59/255, green: 89/255, blue: 152/255, alpha: 1)

}

called via UIColor.facebookBlue or .facebookBlue where appropriate.

So much better right?

For the more curious: the keyword class means that the method/property is called upon the class, not an object of the class. This is very similar to static , which may sound more familiar if you’ve used C++ or Java before.

static is in fact also available in Swift and can be used in place of class , so I was interested to determine the differences. If you use class , the method/property can be overridden in a subclass, while static cannot.

This is a pretty minute detail in this case of creating custom UIColors , but a little more knowledge never hurt!

For people who are still reading: While we’re inside a UIColor extension… Here’s a convenience init I like to use to simplify custom UIColor initialization



convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat {return UIColor(red: r/255, green: g/255, blue: b/255, alpha: a)}

//called via



class var facebookBlue: UIColor {return UIColor(r: 59, g: 89, b: 152, a: 1)}

Hoped you enjoyed!