Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the row of UITextField inside UITableViewCell

I have two UITextFields inside a custom cell of a UITableView. I need to edit and store values of the textFields. When I click inside a UITextField I have to know the row it belongs to in order to save the value to the correct record of a local array. How can I get the row index of the textField? I tried :

-(void)textFieldDidBeginEditing:(UITextField *)textField
{

     currentRow = [self.tableView indexPathForSelectedRow].row;


}

But the currentRow does not change when I click inside the UITextFieldRow.It changes only when I click (select) the entire row...

like image 927
gdm Avatar asked Dec 04 '22 08:12

gdm


2 Answers

The text field did not send touch event to the table view so indexPathForSelectedRow is not working. You can use:

CGPoint textFieldOrigin = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:textFieldOrigin]; 
like image 86
Диляна Тодорова Avatar answered Dec 31 '22 20:12

Диляна Тодорова


In iOS 8 I found that the simulator and device had different number of superviews, so this is a little more generic and should work across all versions of iOS:

UIView *superview = textField.superview;
while (![superview isMemberOfClass:[UITableViewCell class]]) { // If you have a custom class change it here
    superview = superview.superview;
}

UITableViewCell *cell =(UITableViewCell *) superview;
NSIndexPath *indexPath = [self.table indexPathForCell:cell];
like image 25
lewis Avatar answered Dec 31 '22 22:12

lewis