Search code examples
swiftuitableviewuiviewshadow

TableView Cell view shadow does not coming properly in Swift


I have added view as a background for tableview cell and I am giving shadow for view. Here when I run tableview shadow does not coming properly, once I scroll down and up then shadow coming properly.

I have given shadow according to this answer answer

Code:

  extension UIView {
  func dropShadow(scale: Bool = true) {
  layer.masksToBounds = false
  layer.shadowColor = UIColor.black.cgColor
  layer.shadowOpacity = 0.5
  layer.shadowOffset = CGSize(width: -1, height: 1)
  layer.shadowRadius = 1
  layer.shadowPath = UIBezierPath(rect: bounds).cgPath
  layer.shouldRasterize = true
  layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PlansTableViewCell

    cell.containerView.dropShadow()
    return cell
}

Before scrolling shadow coming like this:

enter image description here

after scrolling coming like below:

enter image description here

After running(before scrolling) also i need second image kind of output, Here Help me with the code.


Solution

  • Problem is here

    layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    

    bounds isn't correct at that time , try call it from

    override func layoutSubviews() {
       super.layoutSubviews()
       self.containerViewdropShadow()
    }
    

    or

    cell.layoutIfNeeded()
    cell.containerView.dropShadow()