【问题标题】:table view scrolling smooth with url images使用 url 图像平滑滚动的表格视图
【发布时间】:2014-06-08 19:30:04
【问题描述】:

我有一个从 url 地址加载标题和图像的表格视图。由于我添加了图像,因此滚动不流畅。我已将背景更改为清除。图像分辨率低。我更喜欢使用 url 访问它们,而不是下载图像并在应用程序上重新上传。期待您的解决方案,使滚动顺畅。谢谢

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableCell" forIndexPath:indexPath];
NSString *str = [[feeds objectAtIndex:indexPath.row] objectForKey: @"title"];
[[cell textLabel] setNumberOfLines:0]; // unlimited number of lines
[[cell textLabel] setFont:[UIFont systemFontOfSize: 16.0]];
cell.backgroundColor = [UIColor clearColor];
cell.contentView.backgroundColor = [UIColor clearColor];

cell.TitleLabel.text=str;

UIImage *pImage=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:feeds2[indexPath.row]]]];;
[cell.ThumbImage setImage:pImage];

return cell;

}

【问题讨论】:

  • 在后台线程上加载图像,而不是在主线程上。

标签: ios objective-c uitableview uiimage


【解决方案1】:

在 cellForRowAtIndexPath 中替换您的代码:

在这行之后cell.TitleLabel.text=str;

这样你在后台加载每个图像,一旦加载,相应的单元格就会在 mainThread 上更新。

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
        NSData *imgData =  NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:feeds2[indexPath.row]]];
        if (imgData) {
           UIImage *image = [UIImage imageWithData:imgData];

           dispatch_sync(dispatch_get_main_queue(), ^(void) {
             UIImage *image = [UIImage imageWithData:imgData];
                      if (image) {
                           cell.ThumbImage.image = image;
             }
        });
    });

更好的办法是缓存图片,这样就不需要每次都下载,表格滚动。

这里有一些非常好的参考资料来实现这一点。

LazyTableImages Reference

SDWebImage

UIImageView+AFNetworking

【讨论】:

    【解决方案2】:

    答案很简单,您必须使用NSOperation 实现加载,其中一个自定义类来处理您的下载,并将您的NSOperationQueue 设置为downloadQueue。每个UITableView 都是一个(子类)UIScrollView,因此您可以直接使用这些方法。

    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
        [downloadQueue cancelAllOperations]; // clear your queue
    }
    
    
    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
        if (!decelerate) {
            // start download only for visible cells
        }
    }
    
    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
        // start download only for visible cells
    }
    

    有关更多详细信息,请访问this 教程。在那里您可以真正找到满足您需求的良好解决方案。

    【讨论】:

      猜你喜欢
      • 2012-08-25
      • 2023-03-19
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 2014-05-12
      相关资源
      最近更新 更多