当父视图的 alpha 值为 0.5 时如何使 UIView 不可见 - SWIFT

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

我正在尝试让子视图在其父视图的 alpha 值为 0.5 时不可见。我的代码如下:

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

你可以改变 background color alpha

UIColor.white.withAlphaComponent(alphaValue)

所以将 popUpBackground 代码更新为

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

不设置 parentView 的 alpha,而是将 alpha 设置为 parentView 的背景色。

所以更确切地说:

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

使用:

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