首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >UITableView在滚动到底部时加载更多,就像Facebook应用程序一样

UITableView在滚动到底部时加载更多,就像Facebook应用程序一样
EN

Stack Overflow用户
提问于 2013-11-28 23:11:43
回答 12查看 148.4K关注 0票数 103

我正在开发一个使用SQLite的应用程序。我想显示一个使用分页机制的用户列表(UITableView)。谁能告诉我如何在我的列表中加载更多的数据,当用户滚动到列表的末尾时(就像在Facebook应用程序的主页上)?

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 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

票数 103
EN

Stack Overflow用户

发布于 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.
}
票数 38
EN

Stack Overflow用户

发布于 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];
}
票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20269474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档