Search code examples
swiftuiviewtransparency

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)

Solution

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