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

Rom*_*res 21 uitableview ios swift swift3

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

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

这是我在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
    }
Run Code Online (Sandbox Code Playgroud)

Zon*_*ame 39

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

// we set a variable to hold the contentOffSet before scroll view scrolls
var lastContentOffset: CGFloat = 0

// this delegate is called when the scrollView (i.e 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) {
        // did move up
    } else if (self.lastContentOffset > scrollView.contentOffset.y) {
        // did move down
    } else {
        // didn't move
    }
}
Run Code Online (Sandbox Code Playgroud)

此外:如果您已经使用了子类UIViewController,UIScrollViewDelegate则不需要继承子类UIViewController, UITableViewDelegate因为UITableViewDelegate它已经是子类UIScrollViewDelegate


Ale*_*ara 27

你可以实现scrollViewWillEndDragging方法:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {


    if targetContentOffset.pointee.y < scrollView.contentOffset.y {
        // it's going up
    } else {
        // it's going down
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是答案!! (2认同)