Skip to content

Instantly share code, notes, and snippets.

@joaomvfsantos
Last active May 30, 2023 13:32
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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