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

Swift 文本在表格单元格中重叠,swift,uitableview,parse-platform,Swift,Uitableview,Parse Platform,我在表格视图单元格中创建了一些文本,这些文本进入到UILabel中。当这些表视图单元格更新时,文本自身会重叠,几乎与之前的文本一样,没有删除的内容如下: 代码: finalMatchesBlurUser是从Parses数据库中提取的一个PFUser,当此更改导致名称重叠时,它将被更改 有人能指出发生这种情况的原因吗?每次更新tableview时,它都会检查队列,看看是否可以重用单元格而不是初始化新的单元格。在这种情况下,当它更新时,队列中有单元格,因此每次表更新时都会添加一个新的标签子视图,这

我在表格视图单元格中创建了一些文本,这些文本进入到UILabel中。当这些表视图单元格更新时,文本自身会重叠,几乎与之前的文本一样,没有删除的内容如下:

代码:

finalMatchesBlurUser
是从Parses数据库中提取的一个PFUser,当此更改导致名称重叠时,它将被更改


有人能指出发生这种情况的原因吗?

每次更新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;
     }

每次都会创建UILabel,即使在重复使用单元时也是如此。 解决方案是在Interface Builder中创建UILabel并指定标记(例如100)

然后使用这个代码

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
}

谢谢,现在多了解一点。是否仍需要检查UILabel是否已经生成,如使用if语句?根据您的操作方式,您可以在单元格的子视图中循环,检查标签是否存在,如果存在,只需更改文本即可。如果没有,请创建标签并为其指定标记值。该标记值将是您在初始遍历单元子视图以检查其存在性时检查的值。有意义吗?有点,标记UILabel,如果语句通过标记检查它?我不能从视图中删除名称标签吗?removeFromSubviewmine也可以只更改文本内容,而不是删除它,然后重新添加。希望我的编辑能够澄清我为您的示例所考虑的逻辑。抱歉,还有一个问题,这似乎只适用于名称标签,但正如您在图像中所看到的,我还有两个标签,它们不能正常工作?
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
}