0

I am trying to create a drop shadow for my UITableViewCell's but the CALayer doesn't work like it suppose.

  1. Once it's only on the top of the cell.
  2. Once it's only on the bottom of the cell.
  3. Once it's on the bottom and top of the cell.

My custom cell have :

Global variable:

var l = CALayer()

Next as a cell is going to be reused I have to remove the layer from the super layer.

 override func prepareForReuse() {
        super.prepareForReuse()
        l.removeFromSuperlayer()
    }

I am setting a bounds and inserting the layer inside :

override func layoutSubviews() {
        super.layoutSubviews()
        l.frame = self.bounds
        layer.insertSublayer(l, at: 0)
    }

At the end layer configurations are inside willDisplay cell:

l.backgroundColor = UIColor.rgbColor(red: 221, green: 221, blue: 221, alpha: 1.0).cgColor
            l.position = CGPoint(x: bounds.width / 2, y: -bounds.height / 2 + 0.5)
            l.bounds = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)

            l.shadowColor = UIColor.darkGray.cgColor
            l.shadowOffset = CGSize(width: 0, height: 1)
            l.shadowOpacity = 0.8
            l.shadowRadius = 5.0
            l.zPosition = -1

l does not have cell. before becouse it is all going inside Custom cell methods.

Any ideas what am I missing ? Thanks!

noname
  • 127
  • 1
  • 9
  • I think your need to follow this link: https://stackoverflow.com/questions/39624675/add-shadow-on-uiview-using-swift-3 – Hitesh Aug 27 '17 at 12:06
  • 1
    @Hitesh This link is about how to create a view with a shadow, my question is a bit different. It is all about reusing layers not creating them. – noname Aug 27 '17 at 12:24
  • View is made up of layer, here you are going to add another layer only for making shadow, why not use that view layer. – Hitesh Aug 27 '17 at 12:33
  • @Hitesh The question is about reusing layer. – noname Aug 27 '17 at 12:44
  • 1
    You shouldn't add a layer in `layoutSubviews`. As it's name suggests this method is for computing the layout and not for modifying the view or layer hierarchy. This method can be called multiple times between a `tableView(_:cellForRowAt:)` and a `prepareForReuse()` for the same cell. You should add the layer in `awakeFromNib` from the cell, and not remove it in `prepareForReuse()`. – clemens Aug 27 '17 at 14:31

0 Answers0