1

以下のような動的な tableView があります。これは、に従って配列の名前を示しますindexpath.row。そして、各セルには、以下のコードのように、セルへの削除としての名前を変更するボタンがあります。テーブルをロードするとき、行が次のようにロードされると想定します。

名前1

名前2

名前3

名前4

名前5

名前6

名前7

名前8

次に、ボタンをクリックして、たとえば Name4 を NewName に変更します。ボタンをクリックすると変更されますが、テーブルをスクロールすると、indexpath.row再び Name4 になると (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

配列内の基になるデータを変更し、必要な動作を実現するために TableView をリロードするという rmaddy は正しいです。

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()
}

reloadData を呼び出すには、通常は IBOutlet である UITableView への参照が必要です。コードでは、「tableView」と呼んでいます。resultsNameArray が非常に大きい場合は、数百以上の項目があると考えられます。以下を使用して調査できます。

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

これにより、必要な行だけを更新できます。質問で述べたような少数の行の場合、 reloadData は問題なく、実装が簡単です。

于 2015-10-06T15:37:46.820 に答える