In my app I've got a number of views
that need to be in-place editable
. I've got the tableviewcells
setup to include a UITextField
which is enabled, and the text can be changed and this is fine, it works.
My question is what is the best approach to keeping track of these? Should I :
textfield
. If so then
cell
has the correct field if it's only instantiated once?textfield
added when the cell
is created and simply set its value when configuring the cell
. If so then
cell
went out of view
and then back, its values would be reset to its original value and not the edited value.What approach do you generally tend to use for this scenario? Especially if there are a large number of cells
that you're dealing with.
Store the values for all of your text fields in a mutable array in your data model.
In tableView:willDisplayCell:forRowAtIndexPath:
set your text field's value, using the value from your array based on the index path.
When a text field ends editing, store the value back in the array immediately. There is already a protocol for this (so no need to write your own), but it is a little trickier than normal because you are not handed the indexPath and need to find the one associated with your text field:
- (void) textFieldDidEndEditing:(UITextField *)textField {
CGRect location = [self convertRect:textField.frame toView:self.tableView];
NSIndexPath *indexPath = [[self.tableView indexPathsForRowsInRect:location] objectAtIndex:0];
// Save the contents of the text field into your array:
[yourArray replaceObjectAtIndex:indexPath.row withObject:textField.text];
}
Subclass UITableViewCell and add a UITextField in it's init method.
create a protocol for the custom cell class. when UITextField begin editing or end editing call the delegate's method.
in controller, implement the custom cell's protocol and set the indexpath row value to cell's tag in tableView:cellForRowAtIndexPath:
so every time you edit UITextField, you can know in controller which row is editing (via cell's tag)
The best way is to follow MVC and implement your model, which in your case is the textfield values. What you do is store those values in an array, and in your cellForIndexPath method you reference the correct value in the array. For example, the first row of the table (indexPath.row == 0) would retrieve the first element in the array. Changes in the textField would be recorded on the corresponding element in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With