iOS tableview如何检查它是否向上或向下滚动

我正在学习如何使用TableViews,我想知道如何判断tableView是向上还是向下滚动? 我一直在尝试各种各样的东西,比如这个但是没有用,因为下面是滚动视图,我有一个TableView。 任何建议都会很棒,因为我是新手……

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0 { print("down") } else { print("up") } } 

这是我在tableView代码中的内容

 func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return Locations.count } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == self.Posts.count - 4 { reloadTable(latmin: self.latmin,latmax: self.latmax,lonmin: self.lonmin,lonmax: self.lonmax,my_id: myID) print("Load More") } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HomePageTVC", for: indexPath) as! NewCell cell.post.text = Posts[indexPath.row] cell.fullname.setTitle(FullName[indexPath.row],for: UIControlState.normal) return cell } 

就像@maddy在你的问题的评论中说的那样,你可以通过使用UIScrollViewDelegate来检查你的UITableView是否滚动还有更多你可以通过使用scrollViewDidScrollscrollViewWillBeginDragging函数来检查它滚动到哪个方向。

 // we set a variable to hold the contentOffSet before scroll view scrolls var lastContentOffset: CGFloat = 0 // this delegate is called when the scrollView (ie your UITableView) will start scrolling func scrollViewWillBeginDragging(scrollView: UIScrollView) { self.lastContentOffset = scrollView.contentOffset.y } // while scrolling this delegate is being called so you may now check which direction your scrollView is being scrolled to func scrollViewDidScroll(scrollView: UIScrollView) { if (self.lastContentOffset < scrollView.contentOffset.y) { // moved to top } else if (self.lastContentOffset > scrollView.contentOffset.y) { // moved to bottom } else { // didn't move } } 

此外 :如果已经使用UITableViewDelegateUIViewController子类化,则不需要使用UIScrollViewDelegateUIViewController子类化,因为UITableViewDelegate已经是UIScrollViewDelegate的子类

您可以实现scrollViewWillEndDragging方法:

 func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) { if targetContentOffset.pointee.y < scrollView.contentOffset.y { // it's going up } else { // it's going down } }