文本在表格单元格中重叠 SWIFT

Hen*_*own 3 uitableview parse-platform swift

我有一些文本进入我在表格视图单元格中创建的 UIlabels。当这些表格视图单元格更新时,文本会自我重叠,就像之前的文本没有被删除一样,如下所示:

在此处输入图片说明

代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

这finalMatchesBlurUser是一个从 Parses 数据库中获取的 PFUser,它将发生变化,当这种变化导致名称重叠时。

谁能指出为什么会这样?

Jos*_*met 5

每次更新 tableview 时,它都会检查队列以查看它是否可以重用单元格而不是初始化一个新单元格。在这种情况下,当它更新时,队列中有单元格,因此每次表更新时都会添加一个新的标签子视图,这会导致这种效果。在这种情况下,您应该只添加不存在的标签子视图。否则,只需更新该子视图的文本。

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;
     }
Run Code Online (Sandbox Code Playgroud)