Ios 阵列中的第一个图像未显示在collectionview单元格中
第一个图像未加载,如果我滚动显示collectionview图像,并且我使用了collectionview的autolayout,我认为您应该尝试异步下载图像,而不是同步,类似这样Ios 阵列中的第一个图像未显示在collectionview单元格中,ios,uicollectionview,Ios,Uicollectionview,第一个图像未加载,如果我滚动显示collectionview图像,并且我使用了collectionview的autolayout,我认为您应该尝试异步下载图像,而不是同步,类似这样 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { cell =[self.imgCllvw dequeueReu
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
cell =[self.imgCllvw dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
if(!cell)
{
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
}
NSDictionary *tmpDict = [images objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:@"img"]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imge= [[UIImage alloc]initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = imge;
});
});
cell.layer.borderWidth=1.0f;
cell.layer.borderColor=[UIColor colorWithRed:215.0/255.0 green:214.0/255.0 blue:214.0/255.0 alpha:1.0].CGColor;
return cell;
}
您可以使用dispatch\u sync而不是dispatch\u async,如下所示
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
cell =[self.imgCllvw dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
if(!cell)
{
cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
}
NSDictionary *tmpDict = [images objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:@"img"]];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
UIImage *image = [UIImage imageWithData:data];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
MyCell *cell = (id)[collectionView cellForItemAtIndexPath:indexPath];
if (cell)
cell.imageView.image = image;
});
}
}
}];
[task resume];
cell.layer.borderWidth=1.0f;
cell.layer.borderColor=[UIColor colorWithRed:215.0/255.0 green:214.0/255.0 blue:214.0/255.0 alpha:1.0].CGColor;
return cell;
}
还有一件事,停止引用
UICollectionView
委托和数据源方法中的行
。引用indexPath.item
。但如果我加载更多图像,它会被洗牌,因为在集合单元格中会被重用。正在存储下载的图像数据吗?如果未将其存储在阵列/核心数据中,并在下载前检查图像数据是否存在,然后将其分配给cell image view else download
dispatch_sync(dispatch_get_main_queue(), ^{
cell.imageView.image = imge;
});