我有自定义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
?
答案 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);
}
}