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

import UIKit

extension UIColor{
    
    static func rgb(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
        return UIColor(red: r/255, green: g/255, blue: b/255, alpha: 1)
    }
    
    static let backgroundColor = UIColor.rgb(r: 21, g: 22, b: 33)
    static let primaryColor = UIColor.rgb(r: 227, g: 97, b: 9)
    static let secondaryColor = UIColor.rgb(r: 227, g: 81, b: 62)
    static let tertiaryColor = UIColor.rgb(r: 94, g: 170, b: 206)
    
    
}

 

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