如何根据 tableView 的滚动速度控制函数是不是发生
Posted
技术标签:
【中文标题】如何根据 tableView 的滚动速度控制函数是不是发生【英文标题】:How do I control the whether a function will happen depending on the speed that a tableView is scrolled如何根据 tableView 的滚动速度控制函数是否发生 【发布时间】:2020-08-25 02:37:57 【问题描述】:如果用户以任何速度向下滚动,或者如果用户快速向上滚动(或到达视图控制器的顶部),我希望发生一个动作。我正在使用下面的代码来感知任何移动并实现“确实向上移动”和“确实向下移动”cmets 所在的功能,但我想限制向上移动仅在快速滚动或用户到达时发生tableView 的顶部。我该怎么做?
// 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
// I want this to only occur is the user is scrolling fast
else if self.lastContentOffset > scrollView.contentOffset.y
// did move down
else
// didn't move
【问题讨论】:
【参考方案1】:我想您可以存储调用scrollViewWillBeginDragging
的时间,然后根据scrollViewDidScroll
中的一定时间量测量时间差
var timeScrollingBegan: Date?
func scrollViewWillBeginDragging(_ scrollView: UIScrollView)
// ...
timeScrollingBegan = Date()
func scrollViewDidScroll(_ scrollView: UIScrollView)
if self.lastContentOffset < scrollView.contentOffset.y
// Calculate time difference in milliseconds
let timeDifference = Date().timeIntervalSince(timeScrollingBegan) * 1000
let movementDifference = scrollView.contentOffset.y - lastContentOffset
// If the movement difference is past a certain threshold
// in a certain amount of time, then it is too fast. It will
// take a bit of trial and error to determine the correct threshold
// ...
// You can probably use scrollViewDidEndDecelerating here instead
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)
timeScrollingBegan = nil
【讨论】:
以上是关于如何根据 tableView 的滚动速度控制函数是不是发生的主要内容,如果未能解决你的问题,请参考以下文章