CAGradientLayer已添加到背景,但在顶部呈现

时间:2020-07-04 09:28:02

标签: ios swift

我正在使用以下代码添加背景层:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        gradientLayer.colors = [UIColor.red.cgColor,
                                UIColor.yellow.cgColor,
                                UIColor.green.cgColor,
                                UIColor.blue.cgColor]
    
        view.layer.addSublayer(gradientLayer)

当我运行该应用程序时-背景出现在我拥有的标签的顶部。

但是,当我检查调试视图层次结构时-一切正常显示。检查以下屏幕截图:

enter image description here

我尝试将标签放置在单独的视图中,然后将CAGradientLayer添加到超级视图中,但它仍被绘制在顶部。

您可以在此处检查层次结构:

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试

view.layer.insertSublayer(gradientLayer, at: 0)

经过测试,可与Xcode 12 / iOS 14一起使用

demo

    // just added to some other test controller
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.view.bounds
        gradientLayer.colors = [UIColor.red.cgColor,
                                UIColor.yellow.cgColor,
                                UIColor.green.cgColor,
                                UIColor.blue.cgColor]

        self.view.layer.insertSublayer(gradientLayer, at: 0)  // << here !!
    }