我觉得下面的代码中存在一个小错误,它使得集合视图单元格第一次出现,因为它们很快就会移动,然后到达它们的位置,这是不好的。
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
BookCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"BookCell" forIndexPath:indexPath];
NSString *coverName = [[_dataSource objectAtIndex:indexPath.row] objectForKey:@"cover"];
NSString *cover = [[NSBundle mainBundle] pathForResource:coverName ofType:@"jpg" inDirectory:@"covers"];
cell.coverImage.image = self.placeHolderImage;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *coverImage = [[UIImage alloc] initWithContentsOfFile:cover];
CGSize imageSize = coverImage.size;
UIGraphicsBeginImageContext(imageSize);
[coverImage drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
coverImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
cell.coverImage.image = coverImage;
});
});
...
return cell;
}
更新:如果我将日志放在dispatch_async(dispatch_get_main_queue()
内,我看到每个单元格都在更新两次,这会导致重排效果。但每次例如单元格0具有不同的图像。不确定是什么导致了这一点。
index: 0, cover: <UIImage: 0x156988d0>
index: 1, cover: <UIImage: 0x155b48f0>
index: 3, cover: <UIImage: 0x156b0660>
index: 2, cover: <UIImage: 0x1569d5a0>
index: 4, cover: <UIImage: 0x155eca20>
index: 5, cover: <UIImage: 0x155dece0>
index: 7, cover: <UIImage: 0x155c7d90>
index: 6, cover: <UIImage: 0x155d5920>
index: 8, cover: <UIImage: 0x155c7dc0>
index: 9, cover: <UIImage: 0x155b6d80>
index: 0, cover: <UIImage: 0x155cf410>
index: 1, cover: <UIImage: 0x1569c9a0>
index: 2, cover: <UIImage: 0x15692ca0>
index: 3, cover: <UIImage: 0x1555b7c0>
index: 4, cover: <UIImage: 0x155c9c90>
index: 5, cover: <UIImage: 0x156baee0>
index: 9, cover: <UIImage: 0x155cdf50>
index: 7, cover: <UIImage: 0x155b4630>
index: 8, cover: <UIImage: 0x15684af0>
index: 6, cover: <UIImage: 0x155c7950>
答案 0 :(得分:0)
dispatch_async(dispatch_get_main_queue(), ^{
BookCell *updateCell = (BookCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
if (updateCell)
{
cell.coverImage.image = coverImage;
}
});
此处不需要递归调用。该块可以捕获BookCell
的值,因此您只需要:
dispatch_async(dispatch_get_main_queue(), ^{
cell.coverImage.image = coverImage;
});
设置生成的图像。这可能是您问题的根源。
作为一种风格问题,你在collectionView:cellForItemAtIndexPath:
中做得太多了。在您的自定义BookCell
课程中完成所有这些操作,以便更好地分离问题。