【发布时间】:2013-11-29 04:24:32
【问题描述】:
这是我在 UITableViewDataSource 视图控制器中的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"studentCell";
StudentTableCell *cell = (StudentTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
// Never gets called
}
Student *student = self.studentList[indexPath.row];
cell.nameFirst.text = student.nameFirst;
cell.nameLast.text = student.portrait.assetURL;
// Portrait
CGImageRef portraitRef = [cell.portrait.image CGImage];
CIImage *portraitImage = [cell.portrait.image CIImage];
if (portraitRef == NULL && portraitImage == nil) {
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:[NSURL URLWithString:student.portrait.assetURL] resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef assetRef = [representation fullResolutionImage];
if (assetRef) {
[cell.portrait setImage:[UIImage imageWithCGImage:assetRef]];
}
} failureBlock:^(NSError *error) {}];
}
return cell;
}
这对于适合表格初始滚动位置的前几行按预期工作。
但当我向下滚动时,cell.nameFirst.text 会按预期更改,而 cell.portrait.image 会被回收并开始重复在第一个滚动位置内加载的图像。
问题
- 如何确保每个
cell都有合适的图片 -
cell每个都可以是nil吗?
【问题讨论】:
-
您的自定义单元格正在被重复使用 (
dequeueReusableCellWithIdentifier:),因此创建的第一个单元格中的图像在重复使用时仍然存在。在自定义单元格的prepareForReuse方法中,将纵向图像设置为 nil。 -
我之前尝试过
prepareForReuse,它基本上会导致图像重新加载的无限循环。
标签: ios objective-c uitableview alassetslibrary