How to use Color with RGB or hex value in SwiftUI using Swift 5? [duplicate] - ios

This question already has answers here:
How can I create a UIColor from a hex string?
(49 answers)
Closed 2 years ago.
The community reviewed whether to reopen this question 12 months ago and left it closed:
Original close reason(s) were not resolved
I am currently trying to change the background color of a Label in SwiftUI. As far as I know, SwiftUI takes a View as the parameter for the background Modifier.
However, I encountered a problem I am not able to fix:
I would like to change the background color of my Label by using a hex code or an RGB value. Because of some reason, when doing so the background color always changes to white.
This works perfectly fine:
Label(
title: { Text("someTitle") },
icon: { Image(systemName: "someName") }
)
.background(Color.purple) // Using the provided standard Colors works perfectly fine.
However, I would like to create a background color using a hex or RGB value:
.background(Color(Color.RGBColorSpace.sRGB, red: 92, green: 225, blue: 230, opacity: 1))
// or
.background(Color(UIColor(red: 220, green: 24, blue: 311, alpha: 1)))
This does not work and the background color of the Label always changes back to white. How to achieve this goal?

The UIColor init method UIColor(red:green:blue:alpha) takes float values from 0 to 1 for each value.
Any value ≥ 1.0 is going to "max out" that color. So an expression like UIColor(red: 220, green: 24, blue: 311, alpha: 1) will set all 3 color channels and alpha to 1.0, resulting in white. So would UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
You could create an extension to UIColor that adds convenience initializers that would take values of different types. First, and initializer that would take values from 0-255 for each. Then you could create another intializer UIColor.init(hexString:String).
The one that took values from 0-255 would be a lot easier to write. The one that took hex strings would involve implementing a hex parser. I bet somebody has already written it though.
Take a look at this code, for example:
https://gist.github.com/anonymous/fd07ecf47591c9f9ed1a

Related

SwiftUI - How to generate a random color? [duplicate]

This question already has answers here:
How to make a random color with Swift
(11 answers)
Closed last month.
How to generate a random color in SwiftUI?
I'm surprised there's no such question here...
I saw this post, which picks a color from a collection of colors, but I wanna generate a new one every time...
I've found this video in reddit, with this code:
let randomColor = Color(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1))
works like a charm.

How to create a color with an alpha value using SwiftUI?

In UIKit to create a color with an alpha value there are different ways, for example:
UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
but this method is not available on the corresponding class Color of SwiftUI.
What can I use?
In SwiftUI there is one specific modifier called opacity that can be use to change the alpha level of any colors
Text("Hello world").background(Color.black.opacity(0.8)) // Set the background color as partially transparent.
Additionally the same modifier can be applied to any view, to change its alpha.
Image("myImage").opacity(0.8) //The image will be partially transparent
The color initializer has an opacity parameter:
Color(red: 1.0, green: 0, blue: 1.0, opacity: 0.2)
Apply the opacity modifier to any SwiftUI View like:
RoundedRectangle(cornerRadius: 5)
.fill(Color.yellow)
.frame(width: 50, height: 50)
.opacity(0.5)
Several answers here point to .opacity() method of View. That covers the most common use cases, but perhaps what the OP wants to know is how to create a Color with transparency.
One is to use Color constructor that has the color space, components and opacity, as in the first example below.
If you already have a Color and want a translucent version of it, use the bridges to UIColor like the second example below
let transparentTeal = Color(.sRGB, red: 0.4, green: 1, blue: 0.1, opacity: 0.2)
let red = Color.red
let transparentRed = Color(UIColor(red).withAlphaComponent(0.3))
It seems that now it is possible to use the .opacity method and still return a Color instead of a View:
Documentation:
func opacity(_ opacity: Double) -> Color
Example:
color.opacity(0.5)

Change the text color of a table view cell using rgba [duplicate]

This question already has answers here:
UIColor not working with RGBA values
(6 answers)
Closed 4 years ago.
How do I change the text color of a tableview cell using rgba? I have the following code which is not working. The text color is turning to white when it should be a dark brown.
cell.textLabel?.textColor = UIColor(red: 100, green: 60, blue: 60, alpha: 1.0)
To answer your question:
cell.textLabel?.textColor = UIColor(red: 100/255, green: 60/255, blue: 60/255, alpha: 1.0)
But for a more Xcode 10 way:
Go to the assets folder in your project
Right-click in the area that already has "AppIcon" (outline view) and pick "New Color Set"
Click on the color it should be a white box in the middle of the screen
On the right in the utilities area in the "Color" section click on the "Input Method" drop down and select "8-bit (0-255)"
Now just put in your values i.e. 100, 60, 60, 100%

How to set a custom background color to UIButton?

I was wondering about different types of code for changing the background colour of the button. In my project, I am using:
button4.backgroundColor = UIColor.green
But it only gives me a restricted amount of colour options since it is UIColor. I was wondering if I can write a different piece of code to have more flexibility in the color of the button.
Thanks for any help given.
But it only gives me a restricted amount of colour options since it is
UIColor.
That would be correct when working with the predefined static colors. However, no doubt that you can get another color which is none of the predefined ones.
For instance, consider you have a custom rgb color that you want to use in your app (the button background color), as: red: 100 green: 44 blue: 63, You could get it by using:
init(red:green:blue:alpha:)
Initializes and returns a color object using the specified opacity and
RGB component values.
as follows:
let myCustomRGBColor = UIColor(red: 100.0/255.0, green: 44.0/255.0, blue: 63.0/255.0, alpha: 1.0)
Note that the values are divided on 255.0 because rgb values for the UIColor are between 0 and 1.
Also, note that UIColor has many other initializers for creating a custom color object.

Swift UIView background color opacity

I have a UIView with a UILabel in it. I want the UIView to have white background color, but with an opacity of 50%. The problem whith setting view.alpha = 0.5 is that the label will have an opacity of 50% as well, so I figured out that it maybe would be possible to have a UIView with white background color and opacity (white_view), and then have another UIView with the label (label_view). Then add the "white_view" to "label_view" by doing this: label_view.addSubview(white_view). This apparently doesn't work. I'd like to do like: label_view.backgroundView(white_view) but you can't set a background view on a UIView like you can do in a UICollectionView for instance.
Does anyone have any clue of how to solve this?
EDIT
Because several answers are approx the same I'll type it here.
Now I've tried even these:
label_view1.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
label_view1.addSubview(firstPlacelbl)
endGameView.addSubview(label_view1)
and
label_view1.backgroundColor = UIColor(white: 1, alpha: 0.5)
label_view1.addSubview(firstPlacelbl)
endGameView.addSubview(label_view1)
And still the label is also affected by the alpha, and it gets an opacity of 50%. I don't get it what I do wrong because I only set the colors alpha to 0.5 and not the labels. Any ideas?
You can set background color of view to the UIColor with alpha, and not affect view.alpha:
view.backgroundColor = UIColor(white: 1, alpha: 0.5)
or
view.backgroundColor = UIColor.red.withAlphaComponent(0.5)
Setting alpha property of a view affects its subviews. If you want just transparent background set view's backgroundColor proprty to a color that has alpha component smaller than 1.
view.backgroundColor = UIColor.white.withAlphaComponent(0.5)
For Swift 4.x and above
yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
You can also set it from InterfaceBuilder by changing color's opacity:
The problem you have found is that view is different from your UIView. 'view' refers to the entire view. For example your home screen is a view.
You need to clearly separate the entire 'view' your 'UIView' and your 'UILabel'
You can accomplish this by going to your storyboard, clicking on the item, Identity Inspector, and changing the Restoration ID.
Now to access each item in your code using the restoration ID
The question is old, but it seems that there are people who have the same concerns.
What do you think of the opinion that 'the alpha property of UIColor and the opacity property of Interface Builder are applied differently in code'?
The two views created in Interface Builder were initially different colors, but had to be the same color when the conditions changed.
So, I had to set the background color of one view in code, and set a different value to make the background color of both views the same.
As an actual example, the background color of Interface Builder was 0x121212 and the Opacity value was 80%(in Amani Elsaed's image :: Red: 18, Green: 18, Blue: 18, Hex Color #: [121212], Opacity: 80),
In the code, I set the other view a background color of 0x121212 with an alpha value of 0.8.
self.myFuncView.backgroundColor = UIColor(red: 18, green: 18, blue: 18, alpha: 0.8)
extension is
extension UIColor {
convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(red) / 255.0,
green: CGFloat(green) / 255.0,
blue: CGFloat(blue) / 255.0,
alpha: alpha)
}
}
However, the actual view was
'View with background color specified in Interface Builder': R 0.09 G 0.09 B 0.09 alpha 0.8.
'View with background color by code': R 0.07 G 0.07 B 0.07 alpha 0.8
Calculating it,
0x12 = 18(decimal)
18/255 = 0.07058...
255 * 0.09 = 22.95
23(decimal) = 0x17
So, I was able to match the colors similarly by setting the UIColor values ​​to 17, 17, 17 and alpha 0.8.
self.myFuncView.backgroundColor = UIColor(red: 17, green: 17, blue: 17, alpha: 0.8)
Or can anyone tell me what I'm missing?
It's Simple in Swift . just put this color in your background view color and it will work .
let dimAlphaRedColor = UIColor.redColor().colorWithAlphaComponent(0.7)
yourView.backGroundColor = dimAlphaRedColor

Resources