Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UIView Opacity Programmatically

I'm having quite a hard time messing with UIView's properties to achieve a desired opaque look programmatically that can be easily done through Storyboard and Attributes Inspector.

What I want to re-create (settings from attributes inspector): A UIView with a background color of (RGB Sliders: 0, 0, 0) and Opacity Slider set at 75%, with alpha defaulted at 1. So basically a black UIView with the opacity toned down.

What I've tried programmatically:

1)  view.backgroundColor = .black
    view.alpha = 0.75

2)  view.backgroundColor = UIColor.black.withAlphaComponent(0.75)
    view.isOpaque = true

Attached is a picture of the UIView selected in Storyboard with the settings for you to see. If you need any more information, please don't hesitate to let me know. Much thanks for your help.

Screenshot of Storyboard + attributes inspector

UPDATE: Thanks for all your input. The combination of Clever Error's explanation of view layers and Matt's code allowed for me to achieve my desired look.

Desired UI Look!

like image 848
iMoment Avatar asked Nov 03 '16 15:11

iMoment


People also ask

How do you do opacity in Swift?

Basic Swift Code for iOS AppsView'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.

Is opacity same as Alpha?

Actually "opacity" means "value of alpha-channel" of your UIView . When a view is fully opaque this means its alpha = 1 , when a view is fully transparent (non-opaque) its alpha = 0 . As about properties of CALayer and UIView in Cocoa, yes, they provide the same functionality.


2 Answers

You can set opacity to view like below in Swift 3

view.alpha = CGFloat(0.1)
like image 26
gencaysahinn Avatar answered Nov 01 '22 01:11

gencaysahinn


What you are describing is:

view.backgroundColor = UIColor.black.withAlphaComponent(0.75)
view.isOpaque = false

The view must not be marked opaque, as it is not opaque.

like image 155
matt Avatar answered Nov 01 '22 01:11

matt