1

我有一个如下的动态 tableView,它根据indexpath.row. 在每个单元格中,我都有一个按钮,可以更改名称作为单元格的删除,如下面的代码所示。当我加载表格时,假设行加载如下:

名称1

名称2

名称3

名称4

名称5

名称6

名称7

名称8

然后我单击按钮并将 Name4 更改为 NewName 例如。单击按钮时它会更改,但是当您在表格中滚动时,当再次涉及indexpath.rowName4 时(indexpath.row==3在这种情况下),NewName 会更改回 Name4。每次更改时,如何停止表加载indexpath.row?或者我怎样才能找到解决这个问题的另一种方法?

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

    cell.NameCell1003 = self
    cell.nameLbl.text = self.resultsNameArray[indexPath.row]

    return cell
}

func NameCell1003(cell: NamesCell)
{
    cell.nameLbl.text= "NewName"
}
4

1 回答 1

2

rmaddy 是正确的,您希望更改数组中的基础数据并重新加载 TableView 以实现您想要的行为。

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

    cell.nameLbl.text = self.resultsNameArray[indexPath.row]

    return cell
}

func NameCell1003(cell: NamesCell)
{
    self.resultsNameArray[indexYouWantToChange] = "NewName"
    self.tableView.reloadData()
}

您将需要对 UITableView 的引用,通常这是一个 IBOutlet,以便在其上调用 reloadData。在代码中,我只是将其称为“tableView”。如果您的 resultsNameArray 非常大,考虑超过数百个项目,您可以使用以下方法进行调查:

func reloadRowsAtIndexPaths(_ indexPaths: [NSIndexPath],
           withRowAnimation animation: UITableViewRowAnimation)

这将使您只更新所需的行。对于您在问题中陈述的少量行, reloadData 很好并且更易于实现。

于 2015-10-06T15:37:46.820 回答