gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:06:17 24 4
gpt4 key购买 nike

这是我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com