我有这行代码:
tableView.contentOffset = CGPointMake(0.0f, 10000000.0f);
内容大小远小于10000000.0f
,但UITableView仍然不会滚动到底部。我该怎么办?
答案 0 :(得分:13)
滚动到tableViewCell
?
//for instance, you have 15 cells
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:14 inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
答案 1 :(得分:2)
您可以创建UITableView
的扩展名,并在必要时将其用作常规表格视图方法。
extension UITableView {
let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.height
func scrollToBottom(animated: Bool) {
var y: CGFloat = 0.0
if self.contentSize.height > SCREEN_HEIGHT {
y = self.contentSize.height - SCREEN_HEIGHT
}
self.setContentOffset(CGPointMake(0, y), animated: animated)
}
}
每当内容大小超过屏幕高度时,它将相应地滚动到正确的位置。此方法也适用于AutoLayout。
答案 2 :(得分:0)
试试这段代码:
self.tableView.reloadData()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1, execute: {
let indexPath = IndexPath(row: self.dateSource.count-1, section: 0)
self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true)
})
答案 3 :(得分:0)
UITableView
。extension UITableView {
func scrollTableViewToBottom(animated: Bool) {
guard let dataSource = dataSource else { return }
var lastSectionWithAtLeasOneElements = (dataSource.numberOfSections?(in: self) ?? 1) - 1
while dataSource.tableView(self, numberOfRowsInSection: lastSectionWithAtLeasOneElements) < 1 {
lastSectionWithAtLeasOneElements -= 1
}
let lastRow = dataSource.tableView(self, numberOfRowsInSection: lastSectionWithAtLeasOneElements) - 1
guard lastSectionWithAtLeasOneElements > -1 && lastRow > -1 else { return }
let bottomIndex = IndexPath(item: lastRow, section: lastSectionWithAtLeasOneElements)
scrollToRow(at: bottomIndex, at: .bottom, animated: animated)
}
}
UIScrollView
,但不适用于UITableView
且其单元格多于一个屏幕可以容纳的空间,原因是苹果公司内部对UITableViewController
进行了怪异的内部实现:extension UIScrollView {
func scrollToBottom(animated: Bool) {
guard contentSize.height > bounds.size.height else { return }
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
setContentOffset(bottomOffset, animated: true)
}
}
答案 4 :(得分:0)
不幸的是,我没有足够的代表对此发表评论,但是vol的答案有1个错误,当您在具有0个项目的表视图上调用它时,它会导致无限的while循环,此外它还能正常工作!更正了以下代码:
func scrollToBottom(animated: Bool) {
guard let dataSource = dataSource else { return }
var lastSectionWithAtLeastOneElement = (dataSource.numberOfSections?(in: self) ?? 1) - 1
while dataSource.tableView(self, numberOfRowsInSection: lastSectionWithAtLeastOneElement) < 1 && lastSectionWithAtLeastOneElement > 0 {
lastSectionWithAtLeastOneElement -= 1
}
let lastRow = dataSource.tableView(self, numberOfRowsInSection: lastSectionWithAtLeastOneElement) - 1
guard lastSectionWithAtLeastOneElement > -1 && lastRow > -1 else { return }
let bottomIndex = IndexPath(item: lastRow, section: lastSectionWithAtLeastOneElement)
scrollToRow(at: bottomIndex, at: .bottom, animated: animated)
}