我有这行代码:
tableView.contentOffset = CGPointMake(0.0f, 10000000.0f);
Run Code Online (Sandbox Code Playgroud)
内容大小远小于10000000.0f,但UITableView仍然不会滚动到底部.我该怎么做?
tny*_*lee 14
滚动到tableViewCell?
//for instance, you have 15 cells
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:14 inSection:0];
[self.tableView scrollToRowAtIndexPath:indexPath
atScrollPosition:UITableViewScrollPositionTop
animated:YES];
Run Code Online (Sandbox Code Playgroud)
您可以创建 的扩展UIScrollView,并将其用于 UIScrollView、UITableView 或 UICollectionView 的任何实例。
extension UIScrollView {
func scrollToBottom(animated: Bool) {
var y: CGFloat = 0.0
let HEIGHT = self.frame.size.height
if self.contentSize.height > HEIGHT {
y = self.contentSize.height - HEIGHT
}
self.setContentOffset(CGPointMake(0, y), animated: animated)
}
}
Run Code Online (Sandbox Code Playgroud)
每当内容大小大于滚动视图的高度时,它将相应地滚动到正确的位置。此方法也适用于 AutoLayout。
UITableView,即使有 0 个元素的部分(这会在我在互联网上看到的所有其他解决方案中崩溃)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)
}
}
Run Code Online (Sandbox Code Playgroud)
本主题中 Kevin 的固定版本,防止带有0项目的tableView 无限滚动:
来源:https : //stackoverflow.com/a/59470799/9763761
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)
}
Run Code Online (Sandbox Code Playgroud)
UIScrollView,但不适用于UITableView单元数多于一个屏幕可以容纳的单元格,因为 Apple 奇怪的内部实现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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14433 次 |
| 最近记录: |