swift - 在 swift 中使用颜色的 RGB 值或十六进制值更改 View 的颜色

标签 swift uicolor xcode-6.2

我在网上得到了下面的代码,我在我的项目中使用了这段代码来改变背景的颜色。

// Creates a UIColor from a Hex string.

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

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

    if (countElements(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))
}

当我如下调用上述函数来改变背景颜色时:

lbl91.backgroundColor = colorWithHexString(hex: 0x209624);

它给我以下错误:

cannot convert the expression's type '()' to type integerliteralconvertible

最佳答案

函数需要这样的参数:

colorWithHexString("#ff00dd")

或者没有标签

colorWithHexString("ff00dd")

关于swift - 在 swift 中使用颜色的 RGB 值或十六进制值更改 View 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29297766/

相关文章:

swift - DateFormatter 在 ios 中不起作用通过设置

iphone - 为什么在将 Float 转换为 CGFloat 时 Xcode 给我一个警告 "Cannot convert value of type ' CGFloat' to expected argument type 'UnsafeMutablePointer"?

ios - 在Xcode中制作RGB颜色

xcode - 如何将调试器附加到 Apple Watch 上运行的应用程序?

ios - 向左滑动时在 UITableViewCell 中自定义编辑 View 。 Objective-C 或 Swift

swift - UIColor 可以同时使用深色和浅色模式颜色进行初始化吗?

iOS swift : can't Retrieve current url loaded in UIwebView

swift - 我想在 swift 中使用 outputStream.write() 通过输出流发送 Int

ios - 如何在 iOS 中为自定义属性设置动画

ios - 动画 TabBar 颜色变化