Overlapping text in SWIFT table cells

I have text that goes into UIlabels that I created inside a table view cell. When these table view cells are updated, the text overlaps, almost like the previous text that was not deleted there, for example:

enter image description here

code:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

 let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! UITableViewCell

    var nameLabel = UILabel(frame: CGRectMake(cell.frame.size.width * 0.040, cell.frame.size.height * 0.22, cell.frame.size.width * 0.735, cell.frame.size.height * 0.312))

    var userAtIndexPath = finalMatchesBlurUser[indexPath.row]

    nameLabel.text = userAtIndexPath.username.uppercaseString

    cell.addSubview(nameLabel)
}

      

finalMatchesBlurUser

is a PFUser retrieved from the Parses database that will change when this change results in overlapping names.

Can anyone point out why this is happening?

+3


source to share


2 answers


Every time you refresh the table view, it checks the queue to see if it can reuse the cell instead of initializing a new one. In this case, when it updates, it has cells in the queue, so you add a new subclass of the subclass every time you update the table, which causes this effect. In this case, you should only add the subview if it doesn't already exist. Otherwise, just update the text of this subview.



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! UITableViewCell

         if let nameLabel = cell.viewWithTag(100) as? UILabel{

              var userAtIndexPath = finalMatchesBlurUser[indexPath.row]

              nameLabel.text = userAtIndexPath.username.uppercaseString
         }
         else{
               nameLabel = UILabel(frame: CGRectMake(cell.frame.size.width * 0.040, cell.frame.size.height * 0.22, cell.frame.size.width * 0.735, cell.frame.size.height * 0.312))

               nameLabel.tag = 100;

               var userAtIndexPath = finalMatchesBlurUser[indexPath.row]

               nameLabel.text = userAtIndexPath.username.uppercaseString

               cell.addSubview(nameLabel)
         }
     return cell;
     }

      

+3


source


UILabel is created every time, even when the cell is reused. The solution is to create a UILabel in Interface Builder and assign a tag (eg 100).

Then use this code



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath) as! UITableViewCell
    let nameLabel = cell.viewWithTag(100) as! UILabel
    let userAtIndexPath = finalMatchesBlurUser[indexPath.row]
    nameLabel.text = userAtIndexPath.username.uppercaseString
}

      

+2


source







All Articles