Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
user2099024 Avatar asked Dec 12 '14 07:12

user2099024


People also ask

How do I change the opacity of a color in Swift?

Any SwiftUI view can be partially or wholly transparent using the opacity() modifier. This accepts a value between 0 (completely invisible) and 1 (fully opaque), just like the alpha property of UIView in UIKit.

How do you make a transparent background in Swift?

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values: Background = Clear Color.

What is Alpha in Swift?

Basic Swift Code for iOS Apps View's Alpha value is a floating-point number in the range 0.0 to 1.0, where 0.0 represents totally transparent and 1.0 represents totally opaque. Changing the value of this property updates the alpha value of the current view only.


1 Answers

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)

like image 101
Vitalii Gozhenko Avatar answered Sep 22 '22 20:09

Vitalii Gozhenko