Search code examples
swiftuitableviewswift3shadowpath

Adding shadow to tableview cell cause laggy scroll and duplicate shadow


I have added white space around my tableview cell and every time I scroll this shadows getting bigger and bigger when I scroll, and its get lag when I scroll for the second and third time with the bigger shadow

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell
    cell.backgroundColor = UIColor.clear
    cell.contentView.backgroundColor = UIColor.clear

    let whiteRoundedView : UIView = UIView(frame: CGRect(x:10,y: 5,width: self.view.frame.size.width - 20,height: 117))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
    //whiteRoundedView.layer.masksToBounds = true
    whiteRoundedView.layer.cornerRadius = 5.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: -1,height: 1)
    whiteRoundedView.layer.shadowOpacity = 0.2

    let shadowPath = UIBezierPath(rect: whiteRoundedView.layer.bounds)
    whiteRoundedView.layer.shouldRasterize = true
    whiteRoundedView.layer.shadowPath = shadowPath.cgPath
    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    return cell
}

Solution

  • Just put code inside the awakefrom nib

      class CustomCell: UITableViewCell {
    
    
    
            override func awakeFromNib() {
                super.awakeFromNib()
                // Initialization code
        self.backgroundColor = UIColor.clear
            self.contentView.backgroundColor = UIColor.clear
    
            let whiteRoundedView : UIView = UIView(frame: CGRect(x:10,y: 5,width: self.contentView.frame.size.width - 20,height: 117))
    
            whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [1.0, 1.0, 1.0, 0.9])
            //whiteRoundedView.layer.masksToBounds = true
            whiteRoundedView.layer.cornerRadius = 5.0
            whiteRoundedView.layer.shadowOffset = CGSize(width: -1,height: 1)
            whiteRoundedView.layer.shadowOpacity = 0.2
    
            let shadowPath = UIBezierPath(rect: whiteRoundedView.layer.bounds)
            whiteRoundedView.layer.shouldRasterize = true
            whiteRoundedView.layer.shadowPath = shadowPath.cgPath
            self.contentView.addSubview(whiteRoundedView)
            self.contentView.sendSubview(toBack: whiteRoundedView)
    
            }
    
    
        }