johnDoe
johnDoe

Reputation: 795

How to make a UIView not see through when the parent view has alpha value of 0.5 - SWIFT

I am trying to get a subview to not be see through when its parent view has an alpha value of 0.5. My code is below:

 // Background
 let popUpBackground = UIView.init(frame: self.view.frame)
 popUpBackground.backgroundColor = UIColor.lightGray
 popUpBackground.alpha = 0.5        

 // Popup
 var popUp = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 100))
 popUp.backgroundColor = UIColor.blue
 popUp.alpha = 1.0 // This view appears to inherit the parents alpha value

 // Add popUp as subview to popUpBackground
 popUpBackground.addSubview(popUp)
 self.navigationController?.view.addSubview(popUpBackground)

Upvotes: 0

Views: 232

Answers (2)

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

Do not set the alpha of parentView, rather set the alpha to background color of parentView.

So rather:

let popUpBackground = UIView.init(frame: self.view.frame)
popUpBackground.backgroundColor = UIColor.lightGray
popUpBackground.alpha = 0.5

Use:

let popUpBackground = UIView.init(frame: self.view.frame)
popUpBackground.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)

Upvotes: 0

Abdelahad Darwish
Abdelahad Darwish

Reputation: 6067

you can just change background color alpha

with UIColor.white.withAlphaComponent(alphaValue)

so update popUpBackground code to

 let popUpBackground = UIView.init(frame: self.view.frame)
    popUpBackground.backgroundColor = UIColor.white.withAlphaComponent(0.3)
   // popUpBackground.alpha = 0.1
   self.view.addSubview(popUpBackground)

Upvotes: 1

Related Questions