Search code examples
iosswiftcagradientlayer

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


I'm trying to add a gradient to a UIView that serves as a background (backgroundRect) of a UITableViewCell. I expected the gradient to be drawn at the same Z position as the backgroundRect, however when building on device it obscures (over top of) my labels and other views. What's confusing though is that when I use the ViewDebugger it shows my views as if they should appear with the gradient layer behind them?

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


        }



    }

enter image description here

enter image description here

enter image description here


Solution

  • Just use

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

    Instead of using

    backgroundRect.layer.addSublayer(gradient)