我建议您使用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 解释了如何执行此操作。