Overlay Problem

Hi


I am having problem if i scroll again & again image gets more blacker . It is getting overlapped. I want Overlay effect only once. Below is the code


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        let cell = tblView.dequeueReusableCell(withIdentifier: "cellDetail") as! DetailVCCell

        let dict = testArray.object(at: indexPath.row) as! NSDictionary
      
        let url = URL(string: dict.value(forKey: "aimg") as! String)
cell.imgViewDetail.kf.setImage(with: url)
  
        let overlay: UIView = UIView(frame: CGRect(x:0, y:0, width: cell.imgViewDetail.frame.size.width, height: cell.imgViewDetail.frame.size.height))
overlay.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.1)
cell.contentView.addSubview(overlay)
       
        return cell
    }
  
    private func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return testArray.count
    }


Thanks

Replies

Table views frequently reuse table cells ("dequeueReusableCell(withIdentifier:)"), so the cell you get may already have the subview you added. You should avoiding adding a second overlay if one is already present.


The easiest way to check is to give the overlay a view tag when you create it, but before you create and add the overlay, check if it exists:


     if cell.viewWithTag (42) == nil {  // or any other non-zero number you like
          let overlay - …
          overlay.tag = 42
          cell.contentView.addSubview(overlay)
     }


BTW, you should avoid using colors which specify RGB values directly, because that doesn't account for color management on the device. Instead, use something like this:


     UIColor.black.withAlphaComponent (0.1)