Search code examples
iosswiftuiviewopacity

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!


Solution

  • 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.