我正在开发一个使用SQLite的应用程序。我想显示一个使用分页机制的用户列表(UITableView)。谁能告诉我如何在我的列表中加载更多的数据,当用户滚动到列表的末尾时(就像在Facebook应用程序的主页上)?
发布于 2013-11-28 23:18:29
您可以通过在cellForRowAtIndexPath:
方法中添加对所处位置的检查来做到这一点。这种方法很容易理解和实现:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Classic start method
static NSString *cellIdentifier = @"MyCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier];
}
MyData *data = [self.dataArray objectAtIndex:indexPath.row];
// Do your cell customisation
// cell.titleLabel.text = data.title;
BOOL lastItemReached = [data isEqual:[[self.dataArray] lastObject]];
if (!lastItemReached && indexPath.row == [self.dataArray count] - 1)
{
[self launchReload];
}
}
编辑:添加了对最后一项的检查,以防止递归调用。您必须实现定义是否已到达最后一项的方法。
EDIT2 :解释的lastItemReached
发布于 2014-01-21 14:27:58
最好使用willDisplayCell
方法来检查是否要加载哪个单元格。一旦我们得到当前的indexPath.row
是最后一个,我们就可以加载更多的单元格。这将在向下滚动时加载更多的单元格。
- (void)tableView:(UITableView *)tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// check if indexPath.row is last row
// Perform operation to load new Cell's.
}
发布于 2014-03-29 22:02:41
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
if ((indexPath.section == lastSectionIndex) && (indexPath.row == lastRowIndex)) {
// This is the last cell
[self loadMore];
}
}
如果您使用的是核心数据和NSFetchedResultsController
,则loadMore
可能如下所示:
// Load more
- (void)loadMore {
[self.fetchedResultsController.fetchRequest setFetchLimit:newFetchLimit];
[NSFetchedResultsController deleteCacheWithName:@"cache name"];
NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
[self.tableView reloadData];
}
https://stackoverflow.com/questions/20269474
复制相似问题