我正在尝试从URL获取图像并将其显示在集合视图上该怎么做?我使用了以下代码,但没有得到答案
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
collectionGalleryTechrCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
// NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:Url];
//UIImage *image = [UIImage imageWithData:imageData];
//CollectionViewImage.image = image;
NSURL *urlBack = [NSURL URLWithString:@"http://ssk.com/zpschool1/web/gallery/download%20(4).jpg"];
NSData *urlDataBack = [NSData dataWithContentsOfURL:urlBack];
UIImage *imageBack = [UIImage imageWithData:urlDataBack];
cell.myImg.image =imageBack;
//cell.myImg.image = [UIImage imageWithData:ImgURL];
cell.myImg.userInteractionEnabled=YES;
return cell;
}
异步加载和显示图像比从 URL 获取 NSData 并在 UICollectionView 或 UITableView 中显示 imageWithData 更好。您可以在下面的链接中查看此答案:https://stackoverflow.com/a/34041518/9332509
NSString *strImg_Path = [[NSString alloc]init];
strImg_Path = [NSString stringWithFormat:@"%@",[NSURL URLWithString:@"http://ssk.com/zpschool1/web/gallery/download%20(4).jpg"];
];
[cell.myImg sd_setImageWithURL:[NSURL URLWithString:strImg_Path]
placeholderImage:[UIImage imageNamed:@"placeholer_image"]];
确保默认映像placeholer_image并使用框架 - SDWebImage 进行延迟加载。
将数组中的 URL 用于动态而不是静态 URL。