iosswift

How can I use UIColorFromRGB in Swift?


In Objective-C, we use this code to set RGB color codes for views:

#define UIColorFromRGB(rgbValue)        
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

view.backgroundColor=UIColorFromRGB(0x209624);

How can I use this in Swift?


Solution

  • Here's a Swift version of that function (for getting a UIColor representation of a UInt value):

    func UIColorFromRGB(rgbValue: UInt) -> UIColor {
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
    
    view.backgroundColor = UIColorFromRGB(0x209624)