Swift UIColor extension that extends UIColor with a constructor that accepts hex color values (e.g. #FF0000)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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