简体   繁体   English

表格视图中可见单元格的方法

[英]Method for visible cell in tableview

I want to download an image to my tableViewCell but I only want the image downloaded to be inside a cell who is VISIBLE in my tableview. 我想将图像下载到tableViewCell中,但我只希望下载的图像位于tableview中可见的单元格内。 I want my tableView to download image when the tableviewcell is visible and during that time to display a loading bar or something until the download is finished and then display that image to the corresponding tableviewcell 我希望我的tableView在可见tableviewcell时下载图像,并在此期间显示加载栏或其他内容,直到下载完成,然后将该图像显示到相应的tableviewcell

This is the code I use to display image to tableviewcell: 这是我用来将图像显示到tableviewcell的代码:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("ContentCell", forIndexPath: indexPath)

    let contentCell = cell as! ContentCell

    contentCell.thumbnail.kf_setImageWithURL(self.contentArray[indexPath.row].thumbnailUrl)
    print("row: \(indexPath.row)")


    return contentCell
}

What I get is all the image is download all at once. 我得到的是所有图像一次全部下载。 I know this because When I scroll down I find that all the image is instantly displayed without delay even though my logging method print() only print visible cell's row. 我知道这是因为,当我向下滚动时,即使我的日志记录方法print()只打印可见单元格的行,我也会立即显示所有图像而没有延迟。

Am I implementing this wrong? 我执行这个错误吗?

you will achieve using asynchronous image loading 您将实现使用异步图像加载

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

cell.poster.image = nil; // or cell.poster.image = [UIImage imageNamed:@"placeholder.png"];

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myurl.com/%@.jpg", self.myJson[indexPath.row][@"movieId"]]];

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (data) {
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                MyCell *updateCell = (id)[tableView cellForRowAtIndexPath:indexPath];
                if (updateCell)
                    updateCell.poster.image = image;
            });
        }
    }
}];
[task resume];

return cell;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM