Method to Convert Hexadecimal Color Code into UIColor Swift 5

It’s a common requirement that we have to convert HTML hexadecimal color code into UIColor in swift. Following is a utility method that you can use for that purpose. This code is written in swift 5.

public static func hexStringToUIColor (hex: String) -> UIColor {
        var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        if (cString.hasPrefix("#")) {
            cString.remove(at: cString.startIndex)
        if ((cString.count) != 6) {
            return UIColor.gray
        var rgbValue:UInt32 = 0
        Scanner(string: cString).scanHexInt32(&rgbValue)
        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)

In this method, you need to pass Hex String as a parameter and it will return the UIColor object as a response. You can call this method like

let color = hexStringToUIColor(hex: "#C0C0C0")

That’s it. This is how you can convert Hexadecimal color code into UIColor in Swift.

Here you can find many other Helping code Snippets & Tutorials.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: