Reputation: 309
In my application I need to be able to keep track identify which cell a UITextField comes from when I commit the editing changes in textFieldDidEndEditing:
. To do this, I just set the tag property on the cell's text field in tableview:cellForRowAtIndexPath:
.
When the cells are moved, this causes a bit of trouble. For example, if I move the bottom cell up to the top, delete the cell that is now at the bottom, and then try to edit the cell I just placed at the top, my app will crash because the tag property is still at 8 (or another number), but there aren't this many elements in my datasource.
I tried to fix this problem by updating the tag in tableView:moveRowAtIndexPath:toIndexPath:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSString *siteToMove = [[sites objectAtIndex:[fromIndexPath row]] retain];
[sites removeObjectAtIndex:[fromIndexPath row]];
[sites insertObject:siteToMove atIndex:[toIndexPath row]];
if ([toIndexPath section] == 1) {
[[(BookmarkTextEntryTableViewCell *)[[self tableView] cellForRowAtIndexPath:toIndexPath] textField] setTag:[toIndexPath row]];
}
}
However, this doesn't work because (BookmarkTextEntryTableViewCell *)[[self tableView] cellForRowAtIndexPath:toIndexPath]
returns the cell that was there before moving the row.
Upvotes: 1
Views: 1088
Reputation: 7644
In your - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
method, you can iterate through all the UITextField
s that you might've added as subViews to the table and then check and set the new tag as-
for (UIView* subview in [[self tableView] subviews]) {
if ([subview isKindOfClass:[UITextField class]]) {
if(subview.tag==oldTag){
subview.tag = newTag;
break;
}
}
}
EDIT: On second thought, you can just reload the table data in case that resets all the remaining cell's tags too.
Upvotes: 1