UIColor+Hexcode in iOS


Hi Friends,

I have updated this post to Swift 5.1. This method is used to get  color from Hex.

Swift 5.1

import Foundation
import UIKit

extension UIColor {
    
    /// Hex color
    /// - Parameter hex: hex code
   public class func hexColor (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:UInt64 = 0
        Scanner(string: cString).scanHexInt64(&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 Objctive-C

Download a Category file here

Import the Category File UIColor+HexaCode.h and .m file in to your Project.
and implement this one line code.

colorLbl.backgroundColor = [UIColor colorWithHexString:"F0F0F0"];

– How to make an iOS App
ktrkathir