iOS UITableView滚动到部分的底部

时间:2014-10-02 12:10:44

标签: ios xcode uitableview nsindexpath

我要制作一个包含2个部分的tableview。我可以通过编程方式向每个部分添加单元格,当我添加时,我使用

滚动到tableview的末尾
[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

我的问题是如何滚动到0部分的末尾,这样当用户向第0部分添加单元格时,tableview会动态滚动到第0部分的最后一个单元格。

感谢。

5 个答案:

答案 0 :(得分:22)

您可以尝试使用以下代码:

int yourSection = 2;
int lastRow = [tableView numberOfRowsInSection:yourSection] - 1;
[tableView scrollToRowAtIndexPath:[NSIndexPath lastRow inSection:yourSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

您将获得部分中的行数,然后滚动到该indexPath。

答案 1 :(得分:15)

上述所有建议都是正确的,至少基于文档。但它在我的情况下不起作用 - 我无法让滚动显示表格视图中的最后一行。我不得不在滚动中添加延迟以使其工作。

- (void)scrollToTheBottom:(BOOL)animated
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowCount-1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:animated];
}

我将上述内容称为:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self scrollToTheBottom:YES];
});

答案 2 :(得分:4)

当您在末尾插入行时,您有其索引路径,您可以使用tableview的scrollToIndexPath方法滚动

[self.liveChannelsTable scrollToRowAtIndexPath:IndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

答案 3 :(得分:2)

以防万一,这是Swift中的解决方案:

extension UITableView {
    func scrollToBottom(animated: Bool = true) {
        let sections = self.numberOfSections
        let rows = self.numberOfRowsInSection(sections - 1)
        self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true)
    }
}

答案 4 :(得分:1)

在Swift 3中,它已更新为:

let indexPath = IndexPath(row: self.numberOfRowsInSection(0) - 1), section: 0)
self.commentsTableView.scrollToRow(at: indexPath, at: .bottom, animated: false)
相关问题