ios - 滚动时 TableView 滞后

标签 ios objective-c xcode

我正在尝试实现一个类似于 facebook 或 twitter 时间线的表格。但是当我滚动 UITableView 时,它非常缓慢且滞后。我该如何解决这个问题?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ViewControllerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"htrcell"];
    if (cell==nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"Cell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    NSDictionary *dataArray = [self.threndsArray objectAtIndex:indexPath.row];

    NSURL *url = [NSURL URLWithString:[dataArray objectForKey:@"pic_timeline"]];

    NSData *imgData = [NSData dataWithContentsOfURL:url];

    cell.upload_image.image =[UIImage imageWithData:imgData];

    NSURL *urlimage = [NSURL URLWithString:[dataArray objectForKey:@"pic_user"]];
    NSData *Dataimage = [NSData dataWithContentsOfURL:urlimage];
    cell.uploder_image.image =[UIImage imageWithData:Dataimage];
    cell.uploder_image.clipsToBounds = YES;
    cell.uploder_image.layer.cornerRadius = cell.uploder_image.frame.size.height /2;
    cell.uploder_image.layer.borderWidth = 2.0;
    cell.uploder_image.layer.borderColor = [UIColor whiteColor].CGColor;

    cell.uploder_name.text=[dataArray valueForKeyPath:@"nama_user"];

    cell.like_counter.text=[NSString stringWithFormat:@"%@",[dataArray valueForKeyPath:@"likes"]];

    cell.commenter_name.text=[dataArray valueForKeyPath:@"status_timeline"];

    cell.comments.text=[dataArray valueForKeyPath:@"tgl_timeline"];


    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    return  cell;
}

最佳答案

主要问题是,您在主线程中将图像 url 转换为 NSData,这就是延迟滚动发生的原因。您需要在后台队列中将图像 url 转换为 NSData 并在主队列中更新 UI。

通过这种方式,您可以在后台加载每张图片,一旦加载,相应的单元格就会在主线程上更新。

下面的代码可能对你有帮助

 NSURL *urlimage = [NSURL URLWithString:[dataArray objectForKey:@"pic_user"]];
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
            NSData *Dataimage = [NSData dataWithContentsOfURL:urlimage];
            dispatch_sync(dispatch_get_main_queue(), ^(void) {
             cell.uploder_image.image =[UIImage imageWithData:Dataimage];
            });
    });

关于ios - 滚动时 TableView 滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42710594/

相关文章:

ios - 来自 aws cognito 的忘记密码链接

iOS - 找不到右侧的配置门户选项卡

ios - 在 UILabel 上使用捏合手势调整字体大小和标签框架?

ios - 错误 : The operation couldn’t be completed.(LaunchServicesError 错误 0。)

ios:如何在特定位置启动光标?

iphone - 使用 SBJSON 编写 JSON

xcode - 无法以XCode 6 Swift播放音频

ios - 清除文件内容

ios - 在自定义转换中获取 nil [transitionContext containerView]

ios - NSMutableArray objectAtIndex