我有一个自定义的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

最佳答案

您可以使用 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);
       }
    }
}

注意您不应以这种方式询问表视图,因为它是MVC的V位,并且您已经可以访问M位中的所有数据。

10-06 02:13