我有一个 TableView ,其中包含大量单元格,每个单元格中都有一个 UIImageView。
图像从互联网异步加载,并在每张图像下载后显示在相关单元格中。
我面临的问题是,在加载每张图片之前,我无法点击一个单元格以将其转到与其链接的另一个 View 。
我正在使用 dispatch_async(dispatch_get_global_queue(0, 0), ^{[self getItemImagesAsync:urlArray];});
来启动加载图像的异步进程。
getItemImagesAsync
方法在这里:
- (void) getItemImagesAsync:(NSArray *)urlArray{
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
ResizedImageData = imageArray;
for (NSString *searchString in urlArray) {
if (!shouldContinueLoadingImages) {
return;
}
[imageArray addObject:[self getImageFromURL:searchString]];
ResizedImageData = imageArray;
[self.tableView reloadData];
}
shouldContinueLoadingImages
变量在 View 更改(由于搜索功能)时设置为 false 以停止不必要的图像加载。
所有图像数据都保存在 NSArray ResizedImageData
为了使整个表格不必等待图像下载后再呈现,代码在cellForRowAtIndexPath
方法中使用try 语句来查看图像数据数组中是否存在图像:
@try {
cell.imageView.image = [ResizedImageData objectAtIndex:indexPath.row];
}
@catch (NSException *exception) {}
我在这里缺少一些基本概念,还是有所不同?
最佳答案
这段代码有几个问题。您正在后台线程中重新加载数据。您正在重新加载表格 View 很多。每次重新加载数据时都会抛出多个异常。
有一个更简单的方法:
NSAssert([urlArray count] > indexPath.row, @"There are more rows than image URLs");
NSInteger index = indexPath.row;
NSString *URLString = [urlArray objectAtIndex:index];
// Prep the cell to download the image
cell.imageView.tag = index; // cell needs to remember which image it's downloading.
cell.imageView.image = nil; // Remove the image from the previous use of cell.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Download the image in the background
UIImage *image = [self getImageFromURL:URLString];
dispatch_async(dispatch_get_main_queue(), 0), ^{
// Back on the main thread, set the image in the cell.
if (cell.imageView.tag == index) { // only if the cell is on the same index.
cell.imageView.image = image;
}
});
});
关于ios - 在加载所有图像之前无法点击单元格进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975720/