iOS: 子视图的阴影被父视图覆盖

iOS: Shadow of subview covered by parent view

我有一个包含子视图的视图。我希望子视图有阴影,不被父视图覆盖。如果父视图是透明的,则此方法有效,但如果它不是阴影的一部分,则它会被它覆盖。我尝试设置子视图的 zPosition,但没有用。

这是它的样子:

这是我的代码,您可以将其复制粘贴到 Playground 中:

import UIKit
import PlaygroundSupport

import UIKit

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let myView = MyView(frame: .init(x: 30,
                                         y: 30,
                                         width: 200,
                                         height: 200))

        view.addSubview(myView)
        self.view = view
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

class MyView: UIView {
    let upper = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    private func commonInit() {
        upper.backgroundColor = .red
        upper.translatesAutoresizingMaskIntoConstraints = false
        addSubview(upper)
        
        NSLayoutConstraint.activate([
            upper.topAnchor.constraint(equalTo: topAnchor),
            upper.leadingAnchor.constraint(equalTo: leadingAnchor),
            upper.trailingAnchor.constraint(equalTo: trailingAnchor),
            upper.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.8)
        ])
        
        self.backgroundColor = .yellow
        
        layer.shadowColor = UIColor.blue.cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = .zero
        layer.shadowRadius = 5
        
        // desperate attempts
        upper.layer.zPosition = 1
        upper.layer.masksToBounds = false
        layer.masksToBounds = false
        bringSubviewToFront(upper)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        layer.shadowPath = UIBezierPath(rect: upper.frame).cgPath
    }
}

如果你想让子视图有阴影..像这样给子视图应用阴影

    upper.layer.shadowColor = UIColor.blue.cgColor
    upper.layer.shadowOpacity = 1
    upper.layer.shadowOffset = .zero
    upper.layer.shadowRadius = 5

从这段代码你得到的是这个

如果我弄错了请告诉我,您还需要其他东西...我也会尽力帮助您