Search code examples
swiftuitableviewdelegatesinfinite-loopreloaddata

Reload TableView after clicking on a custom cell's UITextField


I have a tableView with custom cells. Each custom cell has a textfield. When a user clicks on a textfield, I want certain new cells to appear on the screen.

This is what I'm trying:

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    /*
    ...code to determine which new cells should be added in from my data structure
    */
    self.tableView.reloadData()
    return true
}

However, every time reloadData is called, I think the delegate calls textFieldShouldBeginEditing again, so I get stuck in an infinite loop and the method never returns.

Any ideas on how I can avoid this problem?


Solution

  • I think what you are looking for is the insertRowsAtIndexPaths call instead of reloading the whole table.

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

    another stack overflow post you should look at

    here's the link to the Apple docs

    keep in mind you when doing this you need to keep your datasource up to date as well. update the datasource before calling insertRowsAtIndexPath