UIView: 无法添加多个 CALayer,只显示根 CALayer

UIView: cannot add multiple CALayer, only the root one appears

我正在尝试向根视图层添加一些子层。这个想法是为视图混合黄色和红色阴影。

我试过这个:

class ViewController: UIViewController {
    @IBOutlet weak var testView: UIView! {
        didSet {
            testView.backgroundColor = .white
            testView.layer.cornerRadius = 10.0
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        
        testView.layer.shadowColor = UIColor.yellow.cgColor
        testView.layer.shadowOpacity = 1.0
        testView.layer.shadowRadius = 24.0
        
        let layer1 = CALayer()
        layer1.frame = testView.bounds
        layer1.shadowColor = UIColor.red.cgColor
        layer1.shadowOpacity = 1.0
        layer1.shadowRadius = 24.0
        testView.layer.addSublayer(layer1)
    }
}

但是只出现了根层(黄色的),没有出现红色子层:

为什么会这样?感谢您的帮助

两个问题...

  1. 要使图层具有阴影,它必须具有背景颜色。
  2. testView 可能不是它在 viewDidLoad() 中的最终大小...您应该在 viewDidLoad 之后添加层或子类UIView 并在 layoutSubviews
  3. 中设置图层的框架

快速尝试一下:

class SubLayerShadowViewController: UIViewController {

    let testView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        
        testView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(testView)

        let g = view.safeAreaLayoutGuide
        
        NSLayoutConstraint.activate([
            testView.widthAnchor.constraint(equalToConstant: 240.0),
            testView.heightAnchor.constraint(equalTo: testView.widthAnchor),
            testView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            testView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
        ])
        
        testView.backgroundColor = .white
        testView.layer.cornerRadius = 10.0
        
        testView.layer.shadowColor = UIColor.yellow.cgColor
        testView.layer.shadowOpacity = 1.0
        testView.layer.shadowRadius = 24.0

        // move this out of viewDidLoad()
        //let layer1 = CALayer()
        //layer1.cornerRadius = 10.0
        //layer1.frame = testView.bounds
        //layer1.shadowColor = UIColor.red.cgColor
        //layer1.shadowOpacity = 1.0
        //layer1.shadowRadius = 24.0
        //testView.layer.addSublayer(layer1)

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let layer1 = CALayer()
        layer1.cornerRadius = 10.0
        layer1.frame = testView.bounds
        layer1.shadowColor = UIColor.red.cgColor
        layer1.shadowOpacity = 1.0
        layer1.shadowRadius = 24.0
        
        // set this layer's backgroundColor to the view's backgroundColor
        layer1.backgroundColor = testView.backgroundColor?.cgColor

        testView.layer.addSublayer(layer1)

    }

}