TableView 制作相同标签的多个副本,swift

TableView makes multiple copies of same label, swift

出于某种原因,我的单元格标题不断重复。这是代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ContactsTableViewCell

    // Configure the cell...
    cell.contactNumberLabel.text = allNumbers[indexPath.row]

    // App downloads confirmedContactList from server
    // Before data is downloaded confirmedContactList is empty and 'for in' loop crashes app.
    if confirmedContactList != new {

        // Title should appear only in cells where arrays allNumbers and confirmedContactList are identical
        for n in 0..<self.allNumbers.count {
            for k in 0..<self.confirmedContactList.count {
                if self.allNumbers[n] == self.confirmedContactList[k]{
                    cell.nameLabel.text = "This Title Keeps Duplicating"
                }
            }
        }
    }
    return cell
}

基本上,有两个包含电话号码的数组,如果 confirmedContactList 中存在单元格中显示的联系电话,那么 cell.nameLabel 应该说一些具体的内容。

当为已显示的 indexPaths 调用 cellForRowAtIndexPath 方法时,nameLabel 文本未设置为默认值。

如果之前使用的值通过了 confirmedContactList 测试,那么即使新值没有通过测试,您也会看到标题。

只需添加一行就可以了:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ContactsTableViewCell

    // Configure the cell...
    cell.contactNumberLabel.text = allNumbers[indexPath.row]

    // reset the label
    cell.nameLabel.text = ""

    // App downloads confirmedContactList from server
    // Before data is downloaded confirmedContactList is empty and 'for in' loop crashes app.
    if confirmedContactList != new {

        // Title should appear only in cells where arrays allNumbers and     confirmedContactList are identical
        for n in 0..<self.allNumbers.count {
            for k in 0..<self.confirmedContactList.count {
                if self.allNumbers[n] == self.confirmedContactList[k]{
                    cell.nameLabel.text = "This Title Keeps Duplicating"
                }
            }
        }
   }
    return cell
}