How can I create a UIColor from a hex string?

后端 未结 30 1589
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  深忆病人
    2020-11-22 17:14

    Here's a Swift 1.2 version written as an extension to UIColor. This allows you to do

    let redColor = UIColor(hex: "#FF0000")
    

    Which I feel is the most natural way of doing it.

    extension UIColor {
      // Initialiser for strings of format '#_RED_GREEN_BLUE_'
      convenience init(hex: String) {
        let redRange    = Range(start: hex.startIndex.advancedBy(1), end: hex.startIndex.advancedBy(3))
        let greenRange  = Range(start: hex.startIndex.advancedBy(3), end: hex.startIndex.advancedBy(5))
        let blueRange   = Range(start: hex.startIndex.advancedBy(5), end: hex.startIndex.advancedBy(7))
    
        var red     : UInt32 = 0
        var green   : UInt32 = 0
        var blue    : UInt32 = 0
    
        NSScanner(string: hex.substringWithRange(redRange)).scanHexInt(&red)
        NSScanner(string: hex.substringWithRange(greenRange)).scanHexInt(&green)
        NSScanner(string: hex.substringWithRange(blueRange)).scanHexInt(&blue)
    
        self.init(
          red: CGFloat(red) / 255,
          green: CGFloat(green) / 255,
          blue: CGFloat(blue) / 255,
          alpha: 1
        )
      }
    }
    

提交回复
热议问题