向 UITableViewCell 的 UIView(背景视图)添加子层会覆盖其他单元格视图吗?

Adding a sublayer to a UIView (background view) of UITableViewCell covers other cell views?

我正在尝试向用作 UITableViewCell 背景 (backgroundRect) 的 UIView 添加渐变。我希望渐变绘制在与 backgroundRect 相同的 Z 位置,但是在设备上构建时它会遮挡(在顶部)我的标签和其他视图。令人困惑的是,当我使用 ViewDebugger 时,它显示我的视图,就好像它们应该出现在它们后面的渐变层一样?

class NewWorkoutTableViewCell: UITableViewCell {

        @IBOutlet weak var backgroundRect: UIView!

        @IBOutlet weak var dayOfTheWeekLabel: UILabel!

        @IBOutlet weak var sessionTypeLabel: UILabel!
        @IBOutlet weak var dateLabel: UILabel!
        @IBOutlet weak var sessionTypeImage: UIImageView!

        @IBOutlet weak var scoreLabel: UILabel!

        override func awakeFromNib() {
            super.awakeFromNib()

            backgroundRect.layer.cornerRadius = 8.0

            backgroundRect.layer.shadowColor = UIColor.black.cgColor
            backgroundRect.layer.shadowOpacity = 0.5
            backgroundRect.layer.shadowOffset = CGSize(width: 5, height: 5)
            backgroundRect.layer.shadowRadius = 5

            // this is making a CoreAnimation gradient layer
            let gradient = CAGradientLayer() // Line 1

            // this is setting the dimensions of the gradient to the
            // same as the view that will contain it
            gradient.frame = backgroundRect.bounds // Line 2
            //gradient.locations = [0.0, 0.35]
            gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
            gradient.endPoint =  CGPoint(x: 1.0, y: 0.5)


            let iPhoneForegroundColor = UIColor(red:0.22, green:0.26, blue:0.40, alpha:1.0)

            // this is setting the gradient from and to colors
            gradient.colors = [UIColor.white.cgColor,iPhoneForegroundColor.cgColor] // Line 3


            backgroundRect.layer.addSublayer(gradient) // Line 4


        }



    }

只需使用

backgroundRect.layer.insertSublayer(gradient, at: 0) 

而不是使用

backgroundRect.layer.addSublayer(gradient)

调试 UI 并查看添加的图层是否覆盖了子视图...我认为您的图层覆盖了子视图。