Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get UITableViewCell's index from its UITextField?

I have a UITextField in a custom cell inside table. I created new class DataCell which is subclass of UITableViewCell. Inside DataCell I created outlets for textfields and I also have method inside implementation file which uses 'editing did end' and I manipulate textField values there.

I am now wondering how to get rowIndex or number of the cell, as each time I click + button new custom cell is loaded on the table. If I get tag I always get same tag number regardless of the cell I selected.

like image 273
James Douglas Avatar asked Dec 09 '22 16:12

James Douglas


2 Answers

The text field passed to your delegate is a subview of the cell's contentView.

UITableViewCell *cell = (UITableViewCell*) textField.superview.superview; 
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
like image 94
Mundi Avatar answered Dec 11 '22 05:12

Mundi


You can use this logic when you are not sure of hierarchy between textfield and cell.

UITableViewCell *cell = nil;
UIView *parentView = textField.superview;
while(parentView) {
    if([parentView isKindOfClass:[UITableViewCell class]]) {
         cell = parentView;
         break;
    }
    parentView = parentView.superview;
} 

if(cell)
 NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 
like image 27
nkongara Avatar answered Dec 11 '22 07:12

nkongara