在UITableViewCell中获取UITextField行

giu*_*ppe 4 uitableview uitextfield ios

UITextFields在一个自定义单元格中有两个UITableView.我需要编辑和存储textFields的值.当我在里面单击时,UITextField我必须知道它所属的行,以便将值保存到本地数组的正确记录中.如何获取textField的行索引?我试过了 :

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

     currentRow = [self.tableView indexPathForSelectedRow].row;


}
Run Code Online (Sandbox Code Playgroud)

但当我点击UITextFieldRow时,currentRow不会改变.只有当我点击(选择)整行时才会改变...

Дил*_*ова 7

文本字段未向表视图发送触摸事件,因此indexPathForSelectedRow不起作用.您可以使用:

CGPoint textFieldOrigin = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:textFieldOrigin]; 
Run Code Online (Sandbox Code Playgroud)


Kal*_*esh 5

试试这个

//For ios 7

UITableViewCell *cell =(UITableViewCell *) textField.superview.superview.superview;
NSIndexPath *indexPath = [tblView indexPathForCell:cell];


//For ios 6

UITableViewCell *cell =(UITableViewCell *) textField.superview.superview;
NSIndexPath *indexPath = [tblView indexPathForCell:cell];
Run Code Online (Sandbox Code Playgroud)

  • 为什么3次superview? (3认同)
  • 虽然这种方法有效但它肯定会失败并且当苹果公司做出改变时只会引发问题...... (2认同)

Lew*_*s42 5

在iOS 8中,我发现模拟器和设备具有不同数量的超级视图,因此这更加通用,并且应该适用于所有版本的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];
Run Code Online (Sandbox Code Playgroud)