ios - 实现 tableView :cellForRowAtIndexPath: with a ALAssetRepresentation image

标签 ios objective-c uitableview alassetslibrary

这是我在 UITableViewDataSource View Controller 中的方法

- (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 被回收并开始重复在第一个滚动位置内加载的图像。

问题

  1. 如何确保每个 cell 都有合适的图像
  2. cell 都可以是nil吗?

最佳答案

无论是否设置,您都需要更新图像。如果还没有图像,您的代码只会设置图像。滚动时单元格会被重复使用。因此每个单元格都需要使用适合 indexPath 的图像进行更新。

另请注意 assetForURL:resultBlock:failureBlock:。它是异步的。这意味着一旦您在 resultBlock 中获取图像,就需要在主线程上更新单元格。

cell.nameFirst.text = student.nameFirst;
cell.nameLast.text = student.portrait.assetURL;

// Portrait
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) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.portrait setImage:[UIImage imageWithCGImage:assetRef]];
        });
    }
} failureBlock:^(NSError *error) {}];

return cell;

关于ios - 实现 tableView :cellForRowAtIndexPath: with a ALAssetRepresentation image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20271350/

相关文章:

ios - 不应用表格 View 单元格高度

ios - 在 iOS 中验证文本域

iphone - Xcode退出,iOS SDK中出现错误254

ios - 添加和检索单元格到字典丢失单元格信息 swift3

ios - 可重用 UITableHeaderFooterView 松散 ImageView 方向状态

ios - subview 在 Interface Builder 中消失

ios - 在单个条形图中同时显示负水平和正水平

ios - UIScrollView 和 AutoLayout - UIScrollView 过度滚动(底部显示过多空白)

objective-c - OSX/Objective-C 窗口管理 : manipulate the frames & visibility of other applications

ios - 自定义 uitableview 单元格未显示所有文本标签