Swift 5 Convert Hex String to UIColor object - Extension


In swift 5.0 Sometime we feel hard to convert the hex string to UIColor object. This extension will give you more flexibility t you code and it will be more readable


You can simply create object like below.

let color = UIColor(hexString: “#FFFFFF”)


There are two important things to note in this extension,

1) Convenience init method. (Custom init)

2)toHexString Method


import Foundation
import UIKit

extension UIColor {

convenience init(hexString: String, alpha: CGFloat = 1.0) {
   let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
   let scanner = Scanner(string: hexString)
   if (hexString.hasPrefix(“#”)) {
     scanner.scanLocation = 1
   }
   var color: UInt32 = 0
   scanner.scanHexInt32(&color)
   let mask = 0x000000FF
   let r = Int(color >> 16) & mask
   let g = Int(color >> 8) & mask
   let b = Int(color) & mask
   let red = CGFloat(r) / 255.0
   let green = CGFloat(g) / 255.0
   let blue = CGFloat(b) / 255.0
   self.init(red:red, green:green, blue:blue, alpha:alpha)
}

    func toHexString() -> String {
       var r:CGFloat = 0
       var g:CGFloat = 0
       var b:CGFloat = 0
       var a:CGFloat = 0
       getRed(&r, green: &g, blue: &b, alpha: &a)
       let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
       return String(format:”#%06x”, rgb)
    }
}


Let me know if this is worth for you,


Written by Zumry Wahid 2 months ago

are you looking for an ninja app developer ,
yes then it is right time for you to look at my profile.

Do you want to write Response or Comment?

You must be a member of techalyst to proceed!

Continue with your Email ? Sign up / log in

Responses

Be the first one to write a response :(

{{ item.member.name }} - {{ item.created_at_human_readable }}

{{ reply.member.name }} - {{ reply.created_at_human_readable }}