Swift - UITableView scroll event

2019-04-04 00:01发布

I was wondering how to detect if the UITableView is scrolled (up or down). I want to hide the keyboard when the UITableView is scrolled with self.view.endEditing(true).

Thanks in advance

4条回答
太酷不给撩
2楼-- · 2019-04-04 00:22
override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        if(velocity.y>0){
            NSLog("dragging Up");
        }else{
            NSLog("dragging Down");
        }
    }
查看更多
够拽才男人
3楼-- · 2019-04-04 00:36

You can add UIScrollViewDelegate. After that you can implement scrollViewDidScroll method.

查看更多
别忘想泡老子
4楼-- · 2019-04-04 00:37

I believe the complete solution would be the following:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == feedTableView {
        let contentOffset = scrollView.contentOffset.y
        print("contentOffset: ", contentOffset)
        if (contentOffset > self.lastKnowContentOfsset) {
            print("scrolling Down")
            print("dragging Up")
        } else {
            print("scrolling Up")
            print("dragging Down")
        }
    }
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if scrollView == feedTableView {
        self.lastKnowContentOfsset = scrollView.contentOffset.y
        print("lastKnowContentOfsset: ", scrollView.contentOffset.y)
    }
}

The previous answers weren't 100% accurate.

Explanation: scrollViewDidEndDragging will be called when the scrolling stops, therefore we save the last know offset. After that we compare it with the current offset in the delegate method scrollViewDidScroll.

查看更多
SAY GOODBYE
5楼-- · 2019-04-04 00:39

You can set property of UITable view (XCode 7+)

In Storyboard:
In Storyboard

in Code:

tableView.keyboardDismissMode = .onDrag
查看更多
登录 后发表回答