ios - 在加载所有图像之前无法点击单元格进行搜索

标签 ios objective-c uitableview uiimageview

我有一个 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/

相关文章:

iphone - 滚动后检测 UITableView 中的当前顶部单元格

ios - 子类 awakeFromNib 调用父类(super class)自定义 init/setup 方法?

iphone - 选择另一个日历时 EKEvent 标识符发生变化

ios - 文本字段和日期选择器更改值

ios - UITableView 奇怪的 reloadData 问题

ios - ViewController 不确认协议(protocol) UITableViewDataSource

iphone - 创建一个分发给有限选定受众的 iOS 应用程序

objective-c - UIImageView 填充 UIView

objective-c - 如何使用 Cocos2d 给 Sprite 添加 Action

ios - 在 UITableViewCell 的 subview 上设置 mask 层会覆盖自动布局约束