0

view.backgroundColor = UIColor.brownColor()

changes the background but it's limited to few colors, is there a way to use hex color codes?

Justin Rose
  • 1,165
  • 2
  • 10
  • 6

2 Answers2

1

There isn't a built in hex converter, but the one here works well for swift. Also has RGB converter if you prefer that.

How to use hex colour values in Swift, iOS

Code from accepted answer linked above:

extension UIColor {
   convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red <= 255, "Invalid red component")
       assert(green >= 0 && green <= 255, "Invalid green component")
       assert(blue >= 0 && blue <= 255, "Invalid blue component")

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
   }

   convenience init(netHex:Int) {
       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
   }
}

Usage:

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)
var color2 = UIColor(netHex:0xFFFFFF)
Community
  • 1
  • 1
JeffN
  • 1,575
  • 15
  • 26
1

use extensions

    extension UIColor
    {
        class func myGreenColor() -> UIColor
        {
            return UIColor(red: 0.145, green: 0.608, blue: 0.141, alpha: 1.0)/*#259b24*/
        }
     }

this web converts hex to UIColor is objective-c , it should be easy for you to turn objective-c code into swift :P :D

user3703910
  • 624
  • 1
  • 5
  • 25
  • How would I use NSUserDefaults to save the certain color class for the user? If the user selected `myGreenColor()` and it wasn't in viewDidLoad, how would I get it to save the color the user selected? @user3703910 – Justin Rose Dec 30 '14 at 01:40
  • sorry I didn't get your question , can you explain better :D ? – user3703910 Dec 30 '14 at 01:48
  • you should just use a computed var instead of a class function – Leo Dabus Dec 30 '14 at 01:54
  • okay, let's say you have a user that is using your app, and they have 5 choices to choose from the change the background color, green, blue, purple, white, and black. Let's say the user selects blue as their default background color, how would i get that to save so the blue is always the default color for the background? @user3703910 – Justin Rose Dec 30 '14 at 02:24
  • I need to sleep so I'll give a quick solution , the simplest way is to save the user's wanted color in NSUserDefaults (I suggest to make a const string , (like : let myBlackColor = "my black color"), and when the user choses black , save myBlackColor to his NSUserDefaults , and then , in viewDidLoad , make switch (the swifts switch is very powerful ) , and get the color from NSUserDefaults , and change the back ground color . got it ? – user3703910 Dec 30 '14 at 02:34