仅在UITableView中循环遍历textFields

时间:2015-03-05 07:51:54

标签: ios objective-c uitableview for-loop

我有自定义UITableView。我在textFields中有tableView和其他对象。我正在尝试遍历所有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

2 个答案:

答案 0 :(得分:2)

您可以使用isKindOfClass:测试子视图的

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);
       }
    }
}

注意您不应该以这种方式查询tableview,因为它是 MVC V 位并且您已经可以访问所有 M 位内的数据......

答案 1 :(得分:0)

试试这个:

当您将它们作为子视图添加到单元格时,为textField提供唯一标记。例如:取一个恒定值

#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);
    }
}