0

I am currently developing an app that features a UITableView with custom cells that contain a UITextField. The problem I am having is that, after the user inputs a number to the textfield, upon scrolling, the tableView reuses that cell and the user's previous input is initialized in the new cell. For example, if I put the number 7 in the top cell's textfield, when I scroll, the newest cell already has a 7 in it. I am wondering how I can fix this problem? Thank you for any help.

Edit: Since my problem is unclear, I basically need a way for my UITableViewCell to "talk" to the model in my UITableViewController so that when the user is done editing the UITextField in the cell, I can save the input to an array in my view controller. Thanks again

Jared
  • 578
  • 7
  • 21

2 Answers2

2

Override -prepareForReuse in your cell subclass.

In that method, set your text to nil and then call super.prepareForReuse

Nick
  • 2,361
  • 16
  • 27
1

The quick fix is to create an array of integers to represent numbers in the table. Then, in cellForRowAtIndexPath method, just do something like

cell.textField.text = numberArray[indexPath.row]

You need to actually save the text fields data into this array now though, in the same method add

cell.textField.addTarget(self, action: "onTextChanged:", forControlEvents: UIControlEvents.EditingChanged)

Create the ,,onTextChanged'' method like

func onTextChanged(sender: UITextField) {
    let cell = sender.superview! as! UITableViewCell
    let indexPath = self.tableView.indexPathForCell(cell)!
    numberArray[indexPath.row] = sender.text.toInt()!
}
FruitAddict
  • 2,042
  • 15
  • 16
  • how would I update numberArray from the UITableViewCell after the user finishes editing the textfield? I know I can use the textfield delegate method, but how to I access the numberArray from the UITableViewCell class? – Jared Sep 01 '15 at 20:05
  • added the how-to :) This implies that your text field is directly placed in the cell, if it's inside some container you need to add another .superview! to retrieve the cell etc. – FruitAddict Sep 01 '15 at 20:09
  • so is onTextChanged in my UITableViewController class? Thanks for all the help – Jared Sep 01 '15 at 20:15
  • yes. this whole addTarget thingy tells the text field to fire onTextChanged method in the current class (self at the beginning). – FruitAddict Sep 01 '15 at 20:17
  • Yes, it will work for anything that inherits from UIControl. You can even subclass UIControl yourself to create your own widgets and use the same syntax on them. – FruitAddict Sep 01 '15 at 20:19