繁体   English   中英

iOS UITableView滚动到本节底部

[英]iOS UITableView Scroll to bottom of section

我将创建一个包含2个部分的表格视图。 我可以以编程方式将单元格添加到每个部分,当我添加时,我使用滚动到tableview的末尾

[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

我的问题是如何滚动到第0节的末尾,以便当用户将单元格添加到第0节时,tableview动态滚动到第0节的最后一个单元格。

谢谢。

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

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

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

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

- (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];
});

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

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

以防万一,这是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)
    }
}

在Swift 3中,它已更新为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM