提问者:小点点

UIView:不能添加多个CALayer,只显示根CALayer


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

我试过这个:

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个答案

匿名用户

两个问题...

  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)

    }

}