Wednesday, September 23, 2015

Creating Colors with UIColor

The UIColor object lets you store colors and also set colors on objects in your storyboard. The UIColor object comes with some colors built in:


ColorRGB HexSample
UIColor.blackColor()000000
UIColor.darkGrayColor()555555
UIColor.lightGrayColor()aaaaaa
UIColor.whiteColor()ffffff
UIColor.grayColor()808080
UIColor.redColor()ff0000
UIColor.greenColor()00ff00
UIColor.blueColor()0000ff
UIColor.cyanColor()00ffff
UIColor.yellowColor()ffff00
UIColor.magentaColor()ff00ff
UIColor.orangeColor()ff8000
UIColor.purpleColor()800080
UIColor.brownColor()996633

However, there is also a UIColor method init() that lets you specify a custom color that is not in the list above. For example, supposed you wanted to use the color Chocolate, which is not in the above list. The RGB hex values for Chocolate are #D2691E. You could create this color with the following method call:
view.backgroundColor = UIColor.init (
    red: 0.82, green: 0.41, blue: 0.12);
Note that we have to convert the hex numbers to equivalent floating point numbers in the range 0.0 to 1.0 first. If you have the hex colors but not the floating point equivalents, you can build the math into your function call:
view.backgroundColor = UIColor.init (red: CGFloat(0xD2)/255, 
                                   green: CGFloat(0x69)/255, 
                                    blue: CGFloat(0x1E)/255);

Here is a link to the Apple documentation of UIColor.


No comments:

Post a Comment