在 iOS 中,如何使视图具有圆角和阴影遮罩其子视图?

In iOS, how to have view with rounded corners and drop shadow mask its subview?

除了那些紫色的角,我正在尝试创建类似于此图像的内容。请注意蓝色(显示为紫色)contentView 未被其父项 containerView.

剪裁或遮盖

要求是有一个视图:

  1. 有圆角。
  2. 有影子。
  3. 它的子视图不会泄漏到它的外面或它的角落。

这是我正在尝试的代码,但我不确定如何让它发挥作用。

let containerView = UIView(frame: CGRect(x: 300, y: 100, width: 200, height: 200))
containerView.backgroundColor = .green
containerView.layer.cornerRadius = 40
containerView.layer.shadowRadius = 50
containerView.layer.shadowOffset = .zero
containerView.layer.shadowColor = UIColor.red.cgColor
containerView.layer.shadowOpacity = 1
view.addSubview(containerView)

let backgroundLayer = CALayer()
backgroundLayer.frame = containerView.layer.bounds
backgroundLayer.backgroundColor = UIColor.black.cgColor
backgroundLayer.opacity = 0.5
backgroundLayer.cornerRadius = containerView.layer.cornerRadius
backgroundLayer.masksToBounds = true
containerView.layer.addSublayer(backgroundLayer)

let contentView = UIView(frame: containerView.bounds)
contentView.backgroundColor = .blue
contentView.alpha = 0.3

// Omitting this line will produce a green square with rounded corners
// and a red shadow.
containerView.addSubview(contentView)

基于此示例代码,我的一个更具体的问题是为什么设置 masksToBounds = truebackgroundLayer 不屏蔽视图的子视图?

Based on this example code, one of my more specific questions is why doesn't the backgroundLayer which sets masksToBounds = true, mask the view's subview?

因为子视图是视图的子视图,而不是backgroundLayer

视图是图层。剪辑是掩蔽。图层会遮盖自己的绘图及其子图层的绘图。子视图的层 不是 backgroundLayer 的子层。它是它的兄弟,而不是它的 child。您的 view/layer 层次结构如下所示:

    containerView
     |          \
  [layer]   backgroundLayer
     |         (clips itself and its sublayers,
 contentView    but it has no sublayers)
     |
  [layer]