December 2017 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

24 Dec 2017

How to Convert Hex(#C0C0C0) value to UIColor Swift

12/24/2017 10:28:00 pm 0
Hello guys here in this article we are going to learn about converting Hex to UIColor.

First we are creating extension to UIColor as following:

extension UIColor {
 // Code
}

Next add the following two methods inside the color extension as below:

// Create a UIColor from RGB
convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
    self.init(
        red: CGFloat(red) / 255.0,
        green: CGFloat(green) / 255.0,
        blue: CGFloat(blue) / 255.0,
        alpha: a
    )
}

// Create a UIColor from a hex value (E.g 0xC0C0C0)
convenience init(hex: Int, a: CGFloat = 1.0) {
    self.init(
        red: (hex >> 16) & 0xFF,
        green: (hex >> 8) & 0xFF,
        blue: hex & 0xFF,
        a: a
    )
}

We are done for converting Hex to UIColor.

Lets take the following hex value:

Take Silver with hex value as #C0C0C0.

For converting the above hex value add the following line at the start of extension:

static let silver = UIColor(hex: 0xC0C0C0)

That's it now we can use silver color as follow:

let silver  = UIColor.silver


Conclusion:

If you are confused, forget above all lines of code. Simply add the following code :

extension UIColor {
    
    // Create a UIColor from RGB
    convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) {
        self.init(
            red: CGFloat(red) / 255.0,
            green: CGFloat(green) / 255.0,
            blue: CGFloat(blue) / 255.0,
            alpha: a
        )
    }
    // Create a UIColor from a hex value (E.g 0x000000)
    convenience init(hex: Int, a: CGFloat = 1.0) {
        self.init(
            red: (hex >> 16) & 0xFF,
            green: (hex >> 8) & 0xFF,
            blue: hex & 0xFF,
            a: a
        )
    }
}

That's it we can use now as the follow:

let silver  = UIColor(hex: 0xC0C0C0)


Read More

Post Top Ad