我想在iOS tableview中实现分页

我需要在iOS tableview中实现像google这样的横向分页.我们有什么方法可以使用单个tableview来做到这一点吗?你能建议一种方法吗?

解决方法

我建议你使用UICollectionView而不是UITableView.话虽这么说,为了从您的服务器加载分页数据,您需要添加几行代码:
您需要在视图控制器中添加变量才能跟踪数据:
/**
 *  Set this flag when loading data.
 */
@property (nonatomic,assign) BOOL isLoading;


/**
 *  Set this flag if more data can be loaded.
 */
@property (assign,nonatomic) BOOL hasNextPage;


/**
 *  The current page loaded from the server. Used for pagination.
 */
@property (assign,nonatomic) int currentPage;

根据您使用的实现,有不同的实现方法,我们将检查是否是加载数据的正确时间.

UITableView的

在您的UITableViewDelegate实现中添加:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // Check scrolled percentage
    //
    CGFloat yOffset = tableView.contentOffset.y;
    CGFloat height = tableView.contentSize.height - tableView.height;
    CGFloat scrolledPercentage = yOffset / height;


    // Check if all the conditions are met to allow loading the next page
    //
    if (scrolledPercentage > .6f && !self.isLoading && self.hasNextPage)
        [self loadNextPage:++self.currentPage];
}

UICollectionView

并在您的UICollectionViewDelegate实现中添加:

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {

    // Check scrolled percentage
    //
    CGFloat yOffset = collectionView.contentOffset.y;
    CGFloat height = collectionView.contentSize.height - collectionView.height;
    CGFloat scrolledPercentage = yOffset / height;


    // Check if all the conditions are met to allow loading the next page
    //
    if (scrolledPercentage > .6f && !self.isLoading && self.hasNextPage)
        [self loadNextPage:++self.currentPage];

}

然后加载下一页:

- (void)loadNextPage:(int)pageNumber {
    if (self.isLoading) return;
    self.isLoading = YES;

    // Fetch your data here
    // ..

    // Once the request is finished,call this
    self.isLoading = NO;
}

我还建议您检查滚动方向并将其添加为加载下一页的条件.这answer解释了如何执行该操作.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...