UIColor不使用RGBA值

时间:2014-06-19 15:40:30

标签: ios swift uicolor

我正在尝试使用以下代码(RGBA值)更改UITextField中的文本颜色,但它只是显示为白色或清晰,我不太确定,因为背景本身就是白色。

passwordTextField.textColor = UIColor(red: CGFloat(202.0), green: CGFloat(228.0), blue: CGFloat(230.0), alpha: CGFloat(100.0))

passwordTextField.returnKeyType = UIReturnKeyType.Done
passwordTextField.placeholder = "Password"
passwordTextField.backgroundColor = UIColor.clearColor()
passwordTextField.borderStyle = UITextBorderStyle.RoundedRect
passwordTextField.font = UIFont(name: "Avenir Next", size: 14)
passwordTextField.textAlignment = NSTextAlignment.Center
passwordTextField.secureTextEntry = true

6 个答案:

答案 0 :(得分:58)

UIColor的RGB值介于0和1之间(请参阅the documentation“指定为0.0到1.0之间的值”)

您需要将数字除以255:

passwordTextField.textColor = UIColor(red: CGFloat(202.0/255.0), green: CGFloat(228.0/255.0), blue: CGFloat(230.0/255.0), alpha: CGFloat(1.0))

另外,您不需要创建CGFloats:

passwordTextField.textColor = UIColor(red:202.0/255.0, green:228.0/255.0, blue:230.0/255.0, alpha:1.0)

答案 1 :(得分:4)

使用便利初始化(类似专业人士的代码)

第1步

extension UIColor {
    convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: 1)
    }
}

用法

//let color = UIColor(red: 202/255, green: 228/255, blue: 230/255, alpha: 1) ☠️
let color = UIColor(r: 202, g: 228, b: 230) // 

答案 2 :(得分:3)

试试这个:

passwordTextField.textColor = UIColor(red: 0.792, green: 0.894, blue: 0.901, alpha: 1.0

始终放置替代值。 202/255 = 0.792

答案 3 :(得分:2)

红色,绿色,蓝色和alpha应该介于0.0和1.0之间。

答案 4 :(得分:1)

正如其他人所提到的那样,UIColor成分在0.0~1.0的范围内被标准化(我认为宽色域是例外,但还没有进行过研究)。

UIColor类的Conveninet 扩展将允许您使用0~255范围内的值(如从各种检查员和图像编辑工具获得的值):

import UIKit

extension UIColor {

    convenience init(
        redByte   red:UInt8,
        greenByte green:UInt8,
        blueByte  blue:UInt8,
        alphaByte alpha:UInt8
        ) {
        self.init(
            red:   CGFloat(red  )/255.0,
            green: CGFloat(green)/255.0,
            blue:  CGFloat(blue )/255.0,
            alpha: CGFloat(alpha)/255.0
        )
    }
}

答案 5 :(得分:0)

UIColor便捷方法,来自Integers或Hex。

extension UIColor {


    convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")

        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
    }



    convenience init(rgb: Int, alpha: CGFloat = 1) {
        self.init(
            red: (rgb >> 16) & 0xFF,
            green: (rgb >> 8) & 0xFF,
            blue: rgb & 0xFF,
            alpha: alpha
        )
    }
}