Skip to content

Instantly share code, notes, and snippets.

@justin-nodeboy
Last active February 14, 2016 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justin-nodeboy/3da7d8cacf7febc91b9b to your computer and use it in GitHub Desktop.
Save justin-nodeboy/3da7d8cacf7febc91b9b to your computer and use it in GitHub Desktop.
A couple of useful extensions that I found online for Downloading a remote image and setting a hex colour code in Swift
extension UIImageView {
func downloadImageFrom(link link:String, contentMode: UIViewContentMode) {
NSURLSession.sharedSession().dataTaskWithURL( NSURL(string:link)!, completionHandler: {
(data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) {
self.contentMode = contentMode
if let data = data { self.image = UIImage(data: data) }
}
}).resume()
}
}
extension UIColor {
convenience init(colorCode: String, alpha: Float = 1.0) {
//Nice little ammendment from Bionik if you have a copy/paste with the #
if colorCode.containsString("#") { colorCode.removeAtIndex(colorCode.startIndex) }
let scanner = NSScanner(string: colorCode)
var color: UInt32 = 0
scanner.scanHexInt(&color)
let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
}
@Bionik6
Copy link

Bionik6 commented Feb 14, 2016

The UIColor extension allowing the "#" sign, resulting to this:

let yellowColor = UIColor(colorCode: "#e9b71c") 
// or this version
let yellowColor = UIColor(colorCode: "e9b71c")
extension UIColor {
  convenience init(var colorCode: String, alpha: Float = 1.0) {
    if colorCode.containsString("#") { colorCode.removeAtIndex(colorCode.startIndex) }
    let scanner = NSScanner(string: colorCode)
    var color: UInt32 = 0
    scanner.scanHexInt(&color)
    let mask = 0x000000FF
    let r = CGFloat(Float(Int(color >> 16) & mask) / 255.0)
    let g = CGFloat(Float(Int(color >> 8) & mask) / 255.0)
    let b = CGFloat(Float(Int(color) & mask) / 255.0)
    self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha))
  }
}

@justin-nodeboy
Copy link
Author

Amended :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment