UIView background always opaque and white

I am programatically creating a UIView subview of a UIScrollView. The scrollview is black, and I want to set a subview's background's alpha to different values so that different shades of grey show through.


let frame = CGRect(x:0, y:92*position, width:320, height:92)

let view = UIView(frame:frame)


var alpha:CGFloat = 1.0

for _ in 0 ... position { alpha = 3*alpha/4 }


view.layer.backgroundColor = UIColor(red:128, green:128, blue:128, alpha:alpha).cgColor

view.layer.isOpaque = false


With this code, the subview's background is always white. It makes no difference if I set view.backgroundColor and view.isOpaque instead of using the CALayer. Any help greatly appreciated.


Steve.

Answered by Claude31 in 323961022

I see 2 problems :


- you ned to add the subview to the scroll view

        scrollView.addSubview(view)


where scrollView is the IBOutlet you have declared


- In UIColor : parameters must be between 0 and 1.


With 128, it is just as if you said 1 : hence it is all white.

Change to

UIColor(red:0.5, green:0.5, blue:0.5, alpha:alpha)


With these 2 changes, I tested, it works.


Note: you should better rename view (too generic) and call it for instance insideView

Accepted Answer

I see 2 problems :


- you ned to add the subview to the scroll view

        scrollView.addSubview(view)


where scrollView is the IBOutlet you have declared


- In UIColor : parameters must be between 0 and 1.


With 128, it is just as if you said 1 : hence it is all white.

Change to

UIColor(red:0.5, green:0.5, blue:0.5, alpha:alpha)


With these 2 changes, I tested, it works.


Note: you should better rename view (too generic) and call it for instance insideView

Thanks Claude. In fact, I was adding the subview (just didn't bother showing it). The key was forgetting that the UIColor parameters were 0-1 and not 0-255. Thanks again.

UIView background always opaque and white
 
 
Q