UIColor不适用于RGBA值
我正在尝试使用下面的代码(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
UIColor的RGB值在0和1之间(请参阅文档 “指定为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))
另一件事,你不需要创buildCGFloats:
passwordTextField.textColor = UIColor(red:202.0/255.0, green:228.0/255.0, blue:230.0/255.0, alpha:1.0)
试试这个:
passwordTextField.textColor = UIColor(red: 0.792, green: 0.894, blue: 0.901, alpha: 1.0
总是放置替代值。 202/255 = 0.792
红,绿,蓝和阿尔法应该在0.0到1.0之间。
使用便捷的init(代码就像一个专业版)
步骤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) // 😍
正如其他人所提到的, UIColor
组件在UIColor
的范围内正常化(我认为广色域是个例外,但还没有研究过)。
UIColor
类的UIColor
扩展将允许您使用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 ) } }