swift 检测UITableView何时滚动到底部

jjjwad0x  于 2023-02-03  发布在  Swift
关注(0)|答案(5)|浏览(231)

下面的帖子是否仍然是检测UITableView的示例何时滚动到底部[在Swift中]的公认方法,或者它是否被更改(如:改善)之后?
Problem detecting if UITableView has scrolled to the bottom
谢谢你。

wlsrxk51

wlsrxk511#

试试这个:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let height = scrollView.frame.size.height
    let contentYOffset = scrollView.contentOffset.y
    let distanceFromBottom = scrollView.contentSize.height - contentYOffset

    if distanceFromBottom < height {
        print("You reached end of the table")
    }
}

或者你也可以试试这个方法

if tableView.contentOffset.y >= (tableView.contentSize.height - tableView.frame.size.height) {    
    /// you reached the end of the table
}
uqcuzwp8

uqcuzwp82#

雨燕3

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.row + 1 == yourArray.count {
        print("do something")
    }
}
huus2vyu

huus2vyu3#

雨燕4

func scrollViewDidScroll(_ scrollView: UIScrollView) {
  let isReachingEnd = scrollView.contentOffset.y >= 0
      && scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)
}

如果实现可扩展的UITableView/UICollectionView,则可能需要选中scrollView.contentSize.height >= scrollView.frame.size.height

6mzjoqzu

6mzjoqzu4#

**我们可以避免使用scrollViewDidScroll**而使用tableView:willDisplayCell

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.section == tableView.numberOfSections - 1 &&
        indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 {
        // Notify interested parties that end has been reached
    }
}

这应适用于任意数量的节

bfhwhh0e

bfhwhh0e5#

实际公式:

let maxContent =
  table.contentSize.height - table.bounds.height + table.contentInset.bottom

然后。

if table.contentOffset.y < -maxContent {
   // the table is now "pulling" (bouncing) as the user
   // moves their finger upwards more than is possible
}

但请注意:

https://stackoverflow.com/a/71350599/294884
对于非常动态的表,contentSize可能很棘手并且是实时的。

相关问题