UIColor not working with RGBA values

2019-01-02 21:14发布

I am trying to change the text colour in a UITextField using the following code (RGBA value) however it just appears white, or clear, I'm not too sure as the background is white itself.

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

5条回答
大哥的爱人
2楼-- · 2019-01-02 21:43

try this instead :

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

Always put substituted values. 202/255 = 0.792

查看更多
美炸的是我
3楼-- · 2019-01-02 21:50

red, green, blue and alpha are supposed to be between 0.0 and 1.0.

查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 21:56

Using convenience init ( code like a pro )

Step 1

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

Usage

//let color = UIColor(red: 202/255, green: 228/255, blue: 230/255, alpha: 1) ☠️
let color = UIColor(r: 202, g: 228, b: 230) //                                                                     
查看更多
墨雨无痕
5楼-- · 2019-01-02 22:06

As others mentioned, UIColor components are normalized in the range 0.0 ~ 1.0 (I think wide color gamuts are the exception, but haven't researched that yet).

A conveninet extension to the UIColor class will let you use values in the 0~255 range (like those obtained from various inspectors and image editing tools):

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
        )
    }
}
查看更多
冷夜・残月
6楼-- · 2019-01-02 22:08

RGB values for UIColor are between 0 and 1 (see the documentation "specified as a value from 0.0 to 1.0")

You need to divide your numbers by 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))

Another thing, you don't need to create CGFloats:

passwordTextField.textColor = UIColor(red:202.0/255.0, green:228.0/255.0, blue:230.0/255.0, alpha:1.0)
查看更多
登录 后发表回答