Search code examples
iosswiftuitableviewuilabelprepareforreuse

How does one prevent labels of different Swift cells displaying on top of each other?


Screenshot of the double text label

Current constraints of the label

Complete Hirearchy

What is my relevant code currently

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    
    if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? ViewControllerTableViewCell {
        let immy = cell.viewWithTag(1) as? UIImageView
        let person: Userx = people[indexPath.row]
        let text = person.Education
        
        cell.lblName.text = person.Education. ///key line
        cell.lblName.text = text?.uppercased()
        cell.lblName?.layer.masksToBounds = true
       
        let person5 = colorArray[indexPath.row]
        let person6 = colorArray1[indexPath.row]
        let person7 = colorArray2[indexPath.row]
        
    
        let like = cell.viewWithTag(3) as? UIButton
        
        cell.backgroundColor = person5
        like?.backgroundColor = person6
        immy?.backgroundColor = person7
        
        cell.lblName.baselineAdjustment = .alignCenters
        cell.postID = self.people[indexPath.row].postID
        
        cell.row = indexPath.row
        cell.delegate = self
        cell.delegate2 = self
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            like?.isUserInteractionEnabled = true
        }
        return cell
    }
    return UITableViewCell()
}

What have I tried:

In prepare for reuse, I tried lblName.text = "" and lblName.text = nil Didn't work.

I also tried in cellForRowAt:

 cell.lblName.text = nil
 if cell.lblName.text == nil{
 cell.lblName.text = person.Education
}

I also tried to get it done by constraints, no luck.

What I think might be cause

This didn't happen before I changed from TableViewController scene to ViewController(with an output table) scene.

It also didn't happen before I set the cells to have different colors.


Solution

  • I got it to work by checking clear graphics context on label2.