Swift 3.0-16進数色変換UColor

2580 ワード

原文を参照:http://www.jianshu.com/p/345fa430e44
元のビルの主人はswift 2.xを使って編纂して、swift 3.0についてすでに正常に使うことができなくて、だからこのはswift 3.0文法に対して、以下の改正をします。
具体的にどのようにファイルを新規作成しますか?ここではステップを繰り返さず、修正された内容だけを提供します。ありがとうございます。
import UIKit

// MARK: -  UIColor      
extension UIColor {
    /**
     16   UIColor
     
     - parameter hex: 16       
     
     - returns:       
     */
    class func ColorHex(hex: String) -> UIColor {
        return proceesHex(hex: hex, alpha: 1.0)
    }
    
    /**
     16   UIColor,
     
     - parameter hex:   16       
     - parameter alpha:    
     
     - returns:       
     */
    class func ColorHexWithAlpha(hex: String, alpha: CGFloat) -> UIColor {
        return proceesHex(hex: hex, alpha: alpha)
    }
}

// MARK: -     
private func proceesHex(hex: String, alpha: CGFloat) -> UIColor{
    /**            */
    if hex.isEmpty {
        return UIColor.clear
    }
    
    
    /**
          swift3.0   ,        
     */
    
    
    /**      。           、    ,           */
    let set = CharacterSet.whitespacesAndNewlines
    var hHex = hex.trimmingCharacters(in: set).uppercased()
    
    /**             6  */
    if hHex.characters.count < 6 {
        return UIColor.clear
    }
    
    /**     0x    */
    if hHex.hasPrefix("0X") {
        hHex = (hHex as NSString).substring(from: 2)
    }
    /**     #    */
    if hHex.hasPrefix("#") {
        hHex = (hHex as NSString).substring(from: 1)
    }
    /**     ##    */
    if hHex.hasPrefix("##") {
        hHex = (hHex as NSString).substring(from: 2)
    }
    
    /**           6 ,     6       */
    if hHex.characters.count != 6 {
        return UIColor.clear
    }

    /** R G B */
    var range = NSMakeRange(0, 2)
    
    /** R */
    let rHex = (hHex as NSString).substring(with: range)
    
    /** G */
    range.location = 2
    let gHex = (hHex as NSString).substring(with: range)
    
    /** B */
    range.location = 4
    let bHex = (hHex as NSString).substring(with: range)

    /**      */
    var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
    
    Scanner(string: rHex).scanHexInt32(&r)
    Scanner(string: gHex).scanHexInt32(&g)
    Scanner(string: bHex).scanHexInt32(&b)

    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
      :
view.backgroundColor = UIColor.ColorHex(hex: "#f39723")
view.backgroundColor = UIColor.ColorHexWithAlpha(hex: "#f39723", alpha: 0.7)