当用户到达 UITableView 的最后一行时如何动态添加行?

问题描述 投票:0回答:4

我有一个

UITableview
,当前显示 10 行,这是固定静态的。现在我想在其中添加一个功能。当用户到达
UITableView
的最后一行时,我想向表中添加更多 10 行。我的意思是目前我在应用程序中显示固定的 10 行。

但现在我想在用户到达上一个

UITableview
的最后一行时再添加 10 行。

请给我任何建议或任何示例代码来实现我的动机。预先感谢。

iphone uitableview dynamic
4个回答
15
投票

其实很简单。您需要做的是实现

tableView:willDisplayCell:forRowAtIndexPath:
方法,该方法属于
UITableViewDelegate
协议。每次要显示单元格时都会调用此方法。因此,它会让您知道最后一个单元格即将显示的时间。然后你可以做类似的事情-

– (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *) cell forRowAtIndexPath:(NSIndexPath *)indexPath 
{
     if(indexPath.row == [self.array count] - 1) //self.array is the array of items you are displaying
     {
          //If it is the last cell, Add items to your array here & update the table view
     }
}

另一个(有点数学的)选项是实现

UIScrollView
委托方法(
UITableView
UIScrollView
的子类),即
scrollViewDidEndScrollingAnimation:
scrollViewDidScroll:
。这些将使您知道用户正在查看的内容的 y 位置。如果发现最底部的内容可见,您可以添加更多项目。


12
投票

uitableview
源自
uiscrollview
。为了实现您的目标,您需要实施
scrollViewDidEndDecelerating
:

 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    float endScrolling = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (endScrolling >= scrollView.contentSize.height) 
    {
      // your code goes here
    }
}

这将检测到一种“弹跳效果”,例如向上移动可见行以表明人们希望看到更多。


6
投票

您到底想如何调用额外 10 行的加载?当用户向下滚动查看默认加载的前 10 个时,他可能不想再加载 10 个。

您可以添加“添加更多”行作为表格的最后一行。当用户点击这个时,您会再添加 10 个。

(我不知道如何检测“弹跳效应”,例如向上移动可见行以表明人们希望看到更多。)

基本逻辑如下:

  1. cellForRowAtIndexPath
    中,您检查用户是否单击了最后一行,然后调用您的代码来添加 10
  2. 要实际添加 10 条线路,您必须致电
    [myTable reloadData]
  3. 但在调用之前,您需要将
    numberOfRowsInSection
    的返回值增加 10,并确保
    cellForRowAtIndexPath
    将正确返回新行 11-20

ps 如果您确实希望在用户到达表末尾时加载 10 个额外行,则需要在最后一行调用时在

cellForRowAtIndexPath
willDisplayCell:forRowAtIndexPath:
中调用另外 10 行的加载。


1
投票
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [categoriesList count];
}

这里的categoriesList是一个数组。我们可以向该数组添加对象并在 tableview 中调用 reloadData。

© www.soinside.com 2019 - 2024. All rights reserved.