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

3
我正在尝试为充当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


        }



    }

enter image description here

enter image description here

enter image description here


你能展示一下这个单元格的 xib/storyboard 设置吗?同时附上一些图片,展示当前和期望的结果。 - Kamran
1
当然,可以参考上面的@Kamran。 - GarySabo
设置 gradient.zPosition = -1。不确定是否有效,但可以尝试一下。问题在于所有的UI元素都添加在背景矩形中,因此当您添加渐变层时,它会被添加在所有这些元素的顶部。 - Kamran
1
backgroundRect.layer.insertSublayer(gradient, at: 0) 背景矩形层插入渐变层,位置为0。 - iOS Geek
希望这对你有用,@GarySabo。 - iOS Geek
2个回答

9
只需使用 < /p>
backgroundRect.layer.insertSublayer(gradient, at: 0) 

不要使用

backgroundRect.layer.addSublayer(gradient)

谢谢!我该如何获取对这个子层(在0处)的引用,以便我可以将我的投影添加到它上面?否则,阴影会添加到它下面的层? - GarySabo
你正在编写 awakeFromNib() 中的代码,当单元格被初始化时会调用该方法。因此,无论您想要添加像 gradientView 或 shadow 这样的东西,都应该在将其添加到 mainLayer 之前编写。我通常使用的第二个选项是创建不同的 UIView 子类,例如 class GradientView: UIView { /// Add shadow here } 并使用这个类对象作为子视图添加,并将额外的负荷保存在一个类中。 - iOS Geek

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接