如何知道tableView开始滚动

How to know that tableView started scrolling

我有一个疑问:有什么办法可以拦截tableView滚动来给它添加一个动作吗?例如,我的 prototype cell 背景是红色的,在一个单元格内向上触摸它的背景颜色开始是蓝色,然后滚动 tableView 背景颜色 return 红色。 可以这样做吗?!

提前致谢。

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

例如:

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

    }
}

UITableView inherits from UIScrollView and UITableViewDelegate extends UIScrollViewDelegate.

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

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

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

你最好保留一个变量,例如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-CrossFade

这种技术会给你一个很好的用户体验,而不是突然的背景变化。

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

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