如何知道tableView开始滚动

我有一个疑问:有没有办法拦截tableView滚动添加动作? 例如,我的prototype cell背景为红色,在单元格内触摸,其背景颜色开始为蓝色,滚动tableView背景颜色为红色。 是否有可能做到这一点?!

提前致谢。

UITableViewinheritance自UIScrollViewUITableViewDelegate扩展了UIScrollViewDelegate

特别是你可能对scrollViewDidScroll方法感兴趣。 因此,在您的UITableViewDelegate实现中,添加以下方法:

 func scrollViewDidScroll(_ scrollView: UIScrollView) { NSLog("Table view scroll detected at offset: %f", scrollView.contentOffset.y) } 

在设置为tableView委托的ViewController中,您还可以设置scrollView的委托方法。 这些将在滚动tableView时调用,因为它包含scrollView。

例如:

 extension ViewController: UIScrollViewDelegate { func scrollViewDidEndDecelerating(scrollView: UIScrollView) { } } 

你最好保留一个变量,例如var isBackgroundColorRed: Bool = true

将背景颜色设置为蓝色时,另一个用于滚动y位置。 例如

 var blueBackgroundColorYOffset: CGFloat? 

将背景颜色设置为蓝色时,将y偏移设置为contentView.origin.y。

然后在tableview的委托(其子类UIScrollView)

 func scrollViewDidScroll(_ scrollView: UIScrollView) { if !isBackgroundColorRed { // apply some color blending between blue and red based on // the amount of movement on y axis, until you reach the limit // its also important to take the absolute value of the blueBackgroundColorYOffset // and the offset here in scrollViewDidScroll to cover up or down movements // say 1 cell's height, then set your isBackgroundColorRed to true } } 

尝试将此添加到您的项目并更新您的桥接标头。 的UIColor,淡入淡出

这种技术将为您提供良好的用户体验,而不是突然的背景变化。

CellForRow是一种检测滚动的方法,它还为您提供进入视图的下一个单元格的indexPath.row 。 如果用户滚动这么短的距离,甚至没有配置新的或回收的单元,则不会检测到拖动。 但是,即使使用内置方法 (例如scrollViewWillBeginDragging ,也不会检测到短距离滚动。

 var lastCellForRowAtIndex = 0 var isScrollingUp = false func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { isScrollingUp = indexPath.row > lastCellForRowAtIndex lastCellForRowAtIndex = indexPath.row } 

当您滚动tableView时,将重复调用cellForRowAtIndexPath除非您的行数非常少。