1

I have a dynamic tableView as below, which shows names of an array according to indexpath.row. And in each cell I have a button that changes the name which is as a deletage to the cell as in the code below. When I load the table assume the rows load as below:

Name1

Name2

Name3

Name4

Name5

Name6

Name7

Name8

And then I click the button and change Name4 to NewName for example. It is changed when the button is clicked but when you scroll in the table, when it comes to the indexpath.row of Name4 again (where indexpath.row==3 in this case), NewName changes back to Name4. How can I stop the the table to load everytime when the indexpath.row is changing? Or how can I find another solution to this problem?

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"
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
saner
  • 821
  • 2
  • 10
  • 32
  • 2
    A cell's text is based on the data in your `resultsNameArray`. You need to update that array when the button is pressed. – rmaddy Oct 06 '15 at 15:23

1 Answers1

2

rmaddy is correct that you want to change the underlying data in the array and reload the TableView to achieve the behavior you want.

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

You will need a reference to the UITableView, usually this is an IBOutlet, to call reloadData on it. In the code I just called it "tableView". If your resultsNameArray is very large, think more than several hundred items, you might investigate using:

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

That will let you update just the rows you need. For a small number of rows like what you state in your question, reloadData is fine and simpler to implement.

Mr Beardsley
  • 3,743
  • 22
  • 28