仅在 UITableView 中循环遍历 textFields

Loop through textFields ONLY, in UITableView

我有一个习惯UITableView。我在 tableView 中有 textFields 和其他对象。我正在尝试遍历所有 textFields .

这是我的代码:

for (int i = 0; i < [self.rowArray count]; i++) {
    UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    for (UITextField *textField in [cell.contentView subviews]) {
        NSLog(@"%@", textField.text);
    }
}

应用程序崩溃并出现以下错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView text]: unrecognized selector sent to instance 0x7f89eb57b000'

问题显然是它无法对图像进行 NSLog。但它不应该。它本来应该通过 textFields?

您可以使用 isKindOfClass::

测试子视图的 class
for (int i = 0; i < [self.rowArray count]; i++) {
    UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    for (id subview in [cell.contentView subviews]) {
       if ([subview isKindOfClass:[UITextField class]]) {
           UITextField *textField = (UITextField *)subview;
           NSLog(@"%@", textField.text);
       }
    }
}

NOTE 你不应该以这种方式询问表格视图,因为它是 MVC[= 的 V 位22=] 并且您已经可以访问 M 位中的所有数据...

试试这个:

当您将它们作为子视图添加到单元格时,为文本字段提供一个唯一的标签。例如:取一个常量值

#define  kTagTextField   1211

现在 cellForRowAtIndexPath: 执行此操作

[textField setTag:(kTagTextField+indexPath.row)];

以及您希望文本执行此操作的位置

for (int i = 0; i < [self.rowArray count]; i++) {
    UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    if([cell viewWithTag:(kTagTextField+i)]) { 
       UITextField *txtField = [cell viewWithTag:(kTagTextField+i)];
       NSLog(@"%@", textField.text);
    }
}