How to programmatically change the background color of the view [duplicate] - swift

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

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)

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) // 😍

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

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

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
)
}
}

UIColor convenient methods, from Integers, or from 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
)
}
}

Related

How to set alpha for an Assets Color in Swift

I just wanted to know how to change the opacity (alpha) of an asset color I have. When I try this UIColor(named: "something", alpha: 0.4), Xcode complains: Extra argument 'alpha' in call.
Is there any way I can modify the opacity of an asset color programmatically?
UIColor, as mentioned by Jasur S., has the withAlphaComponent(_:).
It can be used with any UIColor objects to modify its alpha:
let color = UIColor(named: "something")?.withAlphaComponent(0.5)
Creating custom extensions to cover existing functionality is an arguable good.
You can add this extension for UIColor and easy to use.
extension UIColor {
convenience init?(named: String, alpha: CGFloat) {
if let rgbComponents = UIColor(named: named)?.cgColor.components {
self.init(red: rgbComponents[0], green: rgbComponents[1], blue: rgbComponents[2], alpha: alpha)
} else {
self.init(named: named)
}
}
}
Usage:
let colorWithAlpha = UIColor(named: "Assets Color", alpha: 0.5)
You can set color alpha component when you assign color as follows:
button.backgroundColor = .black.withAlphaComponent(0.5)
You can modify asset color from here
Select that particular asset color and
Drag that opacity indicator in left or right or directly set some values
Use this extension to get the rgb value from the UIColor
extension UIColor {
var rgba: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return (red, green, blue, alpha)
}
}
Then you can create a new color
let assetColor = UIColor(named: "something")
let (r,g,b,_) = assetColor.rgba
let newColor = UIColor(red:r, green:g, blue:b, alpha: 0.4)

Why does only the built-in UIColors work here? [duplicate]

This question already has answers here:
UIColor not working with RGBA values
(6 answers)
Closed 3 years ago.
Having failed miserably at further attempts to solve this question on my own, I'm trying something I thought would work for certain:
func switchColor(data:UInt32){
switch data {
case 1..<200:
backgroundGeometry.firstMaterial?.diffuse.contents =
UIColor(red: CGFloat(242), green: CGFloat(90), blue: CGFloat(90), alpha: 1.0)
case 200..<400:
backgroundGeometry.firstMaterial?.diffuse.contents =
UIColor(red: CGFloat(252), green: CGFloat(162), blue: CGFloat(115), alpha: 1.0)
case 400..<600:
backgroundGeometry.firstMaterial?.diffuse.contents =
UIColor(red: CGFloat(244), green: CGFloat(235), blue: CGFloat(99), alpha: 1.0)
case 600..<800:
backgroundGeometry.firstMaterial?.diffuse.contents =
UIColor(red: CGFloat(110), green: CGFloat(195), blue: CGFloat(175), alpha: 1.0)
case 800..<1000:
backgroundGeometry.firstMaterial?.diffuse.contents =
UIColor(red: CGFloat(91), green: CGFloat(118), blue: CGFloat(211), alpha: 1.0)
default:
backgroundGeometry.firstMaterial?.diffuse.contents = UIColor.green
}
}
All the non-default cases turns the node white.
The default case does turn it green - and within each case, statements like UIColor.red, UIColor.blue work fine as well.
So why the heck doesn't the above statements work?
Hope you can help, I'm completely at a loss here :(
Edit: Thanks for the swift and not least correct answers! All accepted and upvoted, but I'm too much of a newbie for it to display. Thanks! :)
This should work for you:
func switchColor(data: UInt32) {
guard let contents = backgroundGeometry.firstMaterial?.diffuse.contents else {
fatalError("First material is nil") // If this really can be empty, just replace this with return
}
switch data {
case 1..<200:
contents = UIColor(red: 242/255, green: 90/255, blue: 90/255, alpha: 1)
case 200..<400:
contents = UIColor(red: 252/255, green: 162/255, blue: 115/255, alpha: 1)
case 400..<600:
contents = UIColor(red: 244/255, green: 235/255, blue: 99/255, alpha: 1)
case 600..<800:
contents = UIColor(red: 110/255, green: 195/255, blue: 175/255, alpha: 1)
case 800..<1000:
contents = UIColor(red: 91/255, green: 118/255, blue: 211/255, alpha: 1)
default:
contents = .green
}
}
The maximum value of a color is 1.0, not 255. Therefore you need to divide the values.
According to the documentation, the red, green, blue and alfa values are Float between 0.0 to 1.0 respectively. Also, a value below 0.0 is treated as 0.0 and value above 1.0 is treated as 1.0.
So you must construct the UIColor as this
UIColor(red: 91/255, green: 118/255, blue: 211/255, alpha: 1)
You need to construct them like
UIColor(red:242.0/255.0, green:90.0/255.0, blue:90.0/255.0, alpha: 1.0)
you can find the init in Docs
red/blue/green values below 0.0 are interpreted as 0.0, and values above 1.0 are interpreted as 1.0.
Another note also there is a difference between
90/255 // wrong
and
90.0/255.0 // right
the latter is the correct one as the former will truncate the floating part as it's an integer division

Setting tintColor for Apple Watch complication

I am trying to set the header text color for a Modular Large complication.
I have already customized the watch face to use Multicolor.
However, when I build and run this code, the header text color is still white (which is the default).
Why isn't the color updating?
private func templateForClassModularLarge(className: Schedule) -> CLKComplicationTemplateModularLargeStandardBody {
let template = CLKComplicationTemplateModularLargeStandardBody()
let headerTextProvider = CLKSimpleTextProvider(text: "My Schedule", shortText: "Schedule")
headerTextProvider.tintColor = UIColor(red: 101, green: 153, blue: 255, alpha: 1)
template.headerTextProvider = headerTextProvider
template.body1TextProvider = CLKTimeIntervalTextProvider(startDate: className.start, endDate: className.end)
template.body2TextProvider = CLKSimpleTextProvider(text: className.description, shortText: className.shortDescription)
return template
}
UIColor parameter types are CGFloat, specified as a value from 0.0 to 1.0.
Because your RGB parameters are greater than 1, the color ends up being white, which would be:
UIColor(red: 1, green: 1, blue: 1, alpha: 1)
To fix this issue, simply change your tintColor to
headerTextProvider.tintColor = UIColor(red: 101/255, green: 153/255, blue: 255/255, alpha: 1)

Swift - why NSColor becomes lighter when rendered

I've created NSWindow and made it's background colour absolutely blue (#0000FF). But when the window is rendered, the colour is "lighter" than it should be (#0F3FFB).
class LilWindow: NSViewController {
override func viewDidLoad() {
self.view.window?.backgroundColor =
NSColor.init(red: 0, green: 0, blue: 1, alpha: 1)
}
Does anyone know why it is happening and how to fix this? (screenshot attached)
Okay, so after a couple of hours fiddling with code and #KenThomases help, I figured out that if you want your RGB colours to looks correctly on NSImages and NSWindows, you must convert it into NSDeviceRGBColorSpace colorspace. To do this I've written a simple function:
func toScreenColor(color:NSColor) -> NSColor {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
color
.colorUsingColorSpaceName(NSCalibratedRGBColorSpace)!
.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return NSColor(deviceRed: red, green: green, blue: blue, alpha: alpha)
}

Extra argument in call when using var

I'm trying to use this code:
var alpha : Float
alpha = 0.5
self.view.backgroundColor = UIColor(red: 1, green:0, blue: 0, alpha:alpha)
However, I get the error:
Extra argument 'green' in call
What is wrong with this code? Moreover, why is
self.view.backgroundColor = UIColor(red: 1, green:0, blue: 0, alpha: 0)
working just fine?
Answer was: Swift UIColor initializer - compiler error only when targeting iPhone5s
Use float instead of integers.
UIColor(red: 1.0, green:0.0, blue: 0.0, alpha:alpha)
This also happens when you unwrap the a UIColor instance that wasn't declared as optional.
Instead of:
let brokenColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)!
Use this:
let color: UIColor! = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
If you are using variables use following -
var color: UIColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
My particular iteration of this error happened when I was trying to set the border color of a button, and was getting the "extra argument 'green' in call" error, but once I stored it in a constant the true error arose, which was the constant not being CGColor. So this fixed it.
let borderColor:UIColor = UIColor(red: 23/255, green: 247/255, blue: 252/255, alpha: 1)
loginButton.layer.borderColor = borderColor.CGColor
Put a space after the semicolons in the call
green: 0, alpha: alpha