Skip to content

Instantly share code, notes, and snippets.

@joaomvfsantos
Last active May 30, 2023 13:32
Show Gist options
  • Save joaomvfsantos/b6fbfc55bb79863351717c4cd0a5394c to your computer and use it in GitHub Desktop.
Save joaomvfsantos/b6fbfc55bb79863351717c4cd0a5394c to your computer and use it in GitHub Desktop.
Swift UIColor extension that extends UIColor with a constructor that accepts hex color values (e.g. #FF0000)
//
// UIColorFromHex.swift
//
// Created by João Santos on 14/05/2018.
// Copyright © 2018 João Santos. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init?(hex: String) {
let r, g, b: CGFloat
if hex.hasPrefix("#") {
let start = hex.index(hex.startIndex, offsetBy: 1)
let hexColor = String(hex[start...])
if hexColor.count == 6 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255
g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255
b = CGFloat((hexNumber & 0x0000ff) >> 0) / 255
self.init(red: r, green: g, blue: b, alpha: 1)
return
}
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment