Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIColor not working with RGBA values

Tags:

ios

swift

uicolor

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 
like image 717
Stephen Fox Avatar asked Jun 19 '14 15:06

Stephen Fox


People also ask

How does rgba extend the RGB Colour values?

RGBA Colors RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity for a color. An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

What does the A in rgba () represent?

Alpha, or transparency.

What is RGBA color format?

RGBA is a four-channel format containing data for Red, Green, Blue, and an Alpha value. The CSS function rgb() has wide browser support. The CSS function rgba() may have limited support in the older browser. The opacity of the color cannot be specified using this color format.

How many values does rgba have?

The format of an RGBA value in the functional notation is 'rgba(' followed by a comma-separated list of three numerical values (three integer values), followed by an <alphavalue>, followed by ')'.


2 Answers

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) 
like image 186
bjtitus Avatar answered Oct 09 '22 00:10

bjtitus


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) // 😍 
like image 31
Alwin Avatar answered Oct 08 '22 22:10

Alwin