abh*_*hab 7 pagination uitableview ios
我需要在iOS tableview中实现像google这样的横向分页.我们有什么方法可以使用单个tableview来做到这一点吗?你能建议一种方法吗?
jbo*_*ziz 11
我建议你用一个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;
Run Code Online (Sandbox Code Playgroud)
根据您使用的实现,有不同的实现方法,我们将检查是否是加载数据的正确时间.
在您的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];
}
Run Code Online (Sandbox Code Playgroud)
在您的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];
Run Code Online (Sandbox Code Playgroud)
}
然后加载下一页:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
我还建议您检查滚动方向并将其添加为加载下一页的条件.这个答案解释了如何执行该操作.
您从哪里获取数据?如果您有 API 层,您可以将数据分页构建到 API 方法中。减少来回传递的实际数据量。
您可以使用单个 tableView 来实现此目的。您需要定义部分的数量以及每个部分的项目数量。
| 归档时间: |
|
| 查看次数: |
11991 次 |
| 最近记录: |