7

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!

1
  • It sounds like what you really want is some shade of gray. So why not just create that instead of trying to use transparency?
    – Caleb
    Nov 3, 2016 at 15:32

4 Answers 4

14

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.

1
  • it's background opacity, not view itself
    – user924
    Jan 26, 2018 at 7:19
8

You can set opacity to view like below in Swift 3

view.alpha = CGFloat(0.1)
4

Summarizing these answers https://stackoverflow.com/a/40405424/7767664, https://stackoverflow.com/a/46669162/7767664

for UIView itself opacity

view.isOpaque = false
view.alpha = CGFloat(0.5)

for UIView Background opacity

view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
view.isOpaque = false
0

When your app runs, the view hierarchy will be

UIWindow
    UINavigationControllers view
        Your View Controllers View

The problem is that UIWindow is black by default, and the UINavigationControllers view is clear. So it ends up mixing your transparent black color with full black to get just black.

You would need to add another view to your view controller that is transparent black then set the view controllers view color to the one you want to blend with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.