iOS的自定义表格视图单元格是空
问题描述:
我需要调用一个方法的行被添加到表格视图后,但和我想这iOS的自定义表格视图单元格是空
if (_tableView) {
[self.currentDownloads insertObject:url atIndex:0];
NSLog(@"%@", _currentDownloads);
[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
ACDownloadCell *cell = (ACDownloadCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
[cell downloadFileAtURL:url];
}
else{
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 499) style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:self.tableView];
[self.currentDownloads insertObject:url atIndex:0];
NSLog(@"%@", _currentDownloads);
[self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
ACDownloadCell *cell = (ACDownloadCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
NSLog(@"%@", cell);
[cell downloadFileAtURL:url];
}
,当它记录cell
,它记录(null)
。你看到这里有什么不正确的东西吗?这里是我的tableView:cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
ACDownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"ACDownloadCell" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[ACDownloadCell class]])
{
cell = (ACDownloadCell *)currentObject;
break;
}
}
}
return cell;
}
答
因为重用机制。(如果你使用的cellForRowAtIndexPath获得细胞,细胞可能无法创建或不可见的将返回null。的cellForRowAtIndexPath返回正确只电池(行&部分)是可见)
Xib的称重传感器可能会导致此问题。但如果你通过代码创建单元格不会。
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[ACDownloadCell class]])
{
cell = (ACDownloadCell *)currentObject;
break;
}
}
NSLog(@"cell=%@", cell); // will output null.
}
答
您为重新使用您的单元格的代码看起来看起来很直接和适当。我怀疑你的xib文件搞砸了,你没有将你的单元格划分为ACDownloadCell
。
另外,我觉得你应该考虑升级到使用
registerNib:forCellReuseIdentifier:
更多信息在此可以看出here