滚动到底部时,向UITableView添加行

ahe*_*ang 30 cocoa-touch objective-c uitableview ios

有没有办法触发事件,例如IBAction当用户滚动到底部时UITableView?如果发生这种情况,我想添加更多行.我该怎么做呢?

use*_*351 57

除非有点晚,但我认为我找到了更好的解决方案:

代替

 - (void)scrollViewDidScroll: (UIScrollView)scroll
Run Code Online (Sandbox Code Playgroud)

我用了

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
Run Code Online (Sandbox Code Playgroud)

这样更方便,因为事件只触发一次.我在我的应用程序中使用此代码在我的tableview底部加载更多行(也许你从facebook应用程序中识别出这种类型的重新加载 - 只是它们在顶部更新的区别).

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {    
    NSInteger currentOffset = scrollView.contentOffset.y;
    NSInteger maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height;

    if (maximumOffset - currentOffset <= -40) {
        NSLog(@"reload");
    }
}
Run Code Online (Sandbox Code Playgroud)

希望有人会帮助这个.


Hen*_*mak 38

只需监听scrollViewDidScroll:委托方法,将内容偏移量与当前可能的偏移量进行比较,如果低于某个阈值则调用您的方法来更新tableview.不要忘记打电话[tableView reloadData]确保重新加载新添加的数据.

编辑:汇总抽象代码,不确定它是否有效,但应该.

- (void)scrollViewDidScroll: (UIScrollView *)scroll {
     // UITableView only moves in one direction, y axis
     CGFloat currentOffset = scroll.contentOffset.y;
     CGFloat maximumOffset = scroll.contentSize.height - scroll.frame.size.height;

     // Change 10.0 to adjust the distance from bottom
     if (maximumOffset - currentOffset <= 10.0) {
          [self methodThatAddsDataAndReloadsTableView];
     }
}
Run Code Online (Sandbox Code Playgroud)

  • 我相信这会在contentOffset每次更改时触发,这意味着如果你滚动,这将被触发很多.这让我想起,如果您正在通过网络发出请求,您应该暂时禁用此系统,直到请求正在进行并在添加内容后重新启用.只需在isUpdating的某处添加一个布尔值,然后检查它与偏移差异. (2认同)

Vik*_*ica 13

我用这个片段.在tableView:willDisplayCell:forRowAtIndexPath:我检查,如果具有最后索引路径的单元格即将被显示.

对于包含一个部分的tableView:

[indexPath isEqual:[NSIndexPath indexPathForRow:[self tableView:self.tableView numberOfRowsInSection:0]-1 inSection:0]
Run Code Online (Sandbox Code Playgroud)

更多部分:

[indexPath isEqual:[NSIndexPath indexPathForRow:[self tableView:self.tableView numberOfRowsInSection:0]-1 inSection:[self numberOfSectionsInTableView:self.tableView]-1]
Run Code Online (Sandbox Code Playgroud)
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(!_noMoreDataAvailable)
    {
        if ([indexPath isEqual:[NSIndexPath indexPathForRow:[self tableView:self.tableView numberOfRowsInSection:0]-1 inSection:0]])
        {
            [self.dataSourceController fetchNewData];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

获取dataSourceController后将通知tableView委托,这将重新加载数据.

  • 很棒的答案,更喜欢这个比较scrollViewDidScroll选项 - 感谢vikingosegundo! (2认同)