Swift 4: An extension to define UIColors with “normal” RGB values and set some named colors

UIColors require you to enter red, green and blue as values between 0 and 1. In pracitcal terms that means you need to divide your values by 255 to obtain the CGFloat required. Easy enough? Surely!

Still it is a tad annoying, especially as the rest of the world will give you RGB values between 0 and 255. The below extension to UIColor will add a new method to UIColor that lets you enter rgb values the way you were given them by your designer or the way you’d use them in webdesign, e.g.  UIColor.rgb(r: 227, g: 97, b: 9)  to create a pretty neat orange.

By adding key colors in the extension, you will be able to access them the same as you would a system color, e.g.  UIColor.orange, in other words you’d be able to state  UIColor.primaryColor

 

You Might Also Like