在Swift中将Hex颜色转换为RGB并计算元素

时间:2015-08-30 14:47:39

标签: swift swift2 uicolor

我已经看到了一些答案,说明在这一行使用countElementscount,但我的代码中出现了错误:

if (count(cString) != 6) {

“无法使用count类型的参数列表调用String

我尝试过其他一些想法,但找不到合适的解决方案,任何想法?

这是完整的功能:

func colorWithHexString (hex:String) -> UIColor {
    var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

    if (cString.hasPrefix("#")) {
        cString = (cString as NSString).substringFromIndex(1)
    }

    if (count(cString) != 6) {
        return UIColor.grayColor()
    }

    var rString = (cString as NSString).substringToIndex(2)
    var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
    var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)

    var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
    NSScanner(string: rString).scanHexInt(&r)
    NSScanner(string: gString).scanHexInt(&g)
    NSScanner(string: bString).scanHexInt(&b)


    return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}

1 个答案:

答案 0 :(得分:2)

请尝试使用cString.characters.count

Apple在Swift 2中更新了String,因此它不再符合CollectionType协议,count已定义。相反,Swift字符串现在通过characters属性公开一组字符。

这是因为字符串不一定像其他集合一样 - 例如如果向数组添加数字,则期望该数组的计数增加,但是将某些unicode字符添加到字符串(例如,重音符号)可能不会 增加字符串的长度。

详情请见https://developer.apple.com/swift/blog/?id=30

修改后的方法是:

func colorWithHexString (hex:String) -> UIColor {
 var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

  if (cString.hasPrefix("#")) {
    cString = (cString as NSString).substringFromIndex(1)
  }

  if (cString.characters.count != 6) {
    return UIColor.grayColor()
  }

  let rString = (cString as NSString).substringToIndex(2)
  let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
  let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)

  var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
  NSScanner(string: rString).scanHexInt(&r)
  NSScanner(string: gString).scanHexInt(&g)
  NSScanner(string: bString).scanHexInt(&b)


  return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}

请注意,有些vars已成为let,因为它们永远不会发生变异