在 UITableView 中从网络预加载数据

Preloading data from network in UITableView

我有一个页面在从网络加载数据时支持分页。

我正在使用 UITableview 来显示列表。

我想在用户滚动到当前页面末尾时预加载下一页。

例如,每个页面有 10 个项目。当项目 8 在屏幕上可见时,我将立即开始加载下一页。

UITableView 的哪个委托方法是这个任务的最佳选择?

UITableView 是UIScrollView 的子类,因此您可以使用它委托方法。我建议你使用这两个:

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    if (!decelerate) {
         NSSet *visibleRows = [NSSet setWithArray:[self.view.tableView indexPathsForVisibleRows]];

    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    NSSet *visibleRows = [NSSet setWithArray:[self.view.tableView indexPathsForVisibleRows]];

}

在获取 visibleRows 并预加载数据后检查您的子句,例如,如果 NSSet 中的最后一个 indexPath.row 等于您的数据源数组计数(或等于 [array count] - some_number_you_want )

要存档,当 tableView 开始滚动时,您可以在此处实现预加载逻辑:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    NSSet *visibleRows = [NSSet setWithArray:[self.view.tableView indexPathsForVisibleRows]];
// your update code here
}

希望对您有所帮助。

UITableViewDelegate中添加此方法:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{   
    CGFloat height = scrollView.frame.size.height;

    CGFloat yOffset = scrollView.contentOffset.y;

    CGFloat distanceFromBottom = scrollView.contentSize.height - yOffset;

    if(distanceFromBottom < height) 
    {
        NSLog(@"end of the table and call web service or load more data");
    }
}

试试下面的方法,就会知道显示单元格了

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath
    {
//      Webservice Call for next 10 display data
    }

讨论 table 视图在使用单元格绘制行之前将此消息发送给它的委托,从而允许委托在显示之前自定义单元格对象。此方法使委托有机会覆盖先前由 table 视图

设置的基于状态的属性

使用 UITableViewDataSourcePrefetching or UICollectionViewDataSourcePrefetching 从网络预加载数据,并在向用户显示时准备好您的单元格