How to know that tableView started scrolling

2019-04-25 02:24发布

问题:

I have a doubt: is there any way to intercept a tableView scrolling to add it an action? For example my prototype cell background is red, touching up inside a cell its background color begin blue and scrolling the tableView background color return red. Is it possible to do this?!

Thanks in advance.

回答1:

UITableView inherits from UIScrollView and UITableViewDelegate extends UIScrollViewDelegate.

Particularly you may be interested in scrollViewDidScroll method. So, in your UITableViewDelegate implementation, add the following method:

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


回答2:

In the ViewController that is set as the delegate for the tableView, you can also set the delegate methods of a scrollView. These will be called when the tableView is scrolled as it contains a scrollView.

e.g:

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

    }
}


回答3:

You are better of keeping a variable around e.g. var isBackgroundColorRed: Bool = true

And another for scroll y position when you set the background color to blue. e.g.

var blueBackgroundColorYOffset: CGFloat?

When you set the background color to blue, set the y offset, to the contentView.origin.y.

Then in the delegate for the tableview (which subclasses 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
    }
}

Try adding this to your project and update yur bridging header. UIColor-CrossFade

This technique will give you a nice UX rather than a sudden background change.



回答4:

CellForRow is a way to detect scrolling which also gives you the indexPath.row of the next cell entering the view. If the user scrolls such a short distance that a new or recycled cell is not even configured, then dragging will not be detected. However even with built in methods, such as scrollViewWillBeginDragging, short distance scrolling will not be detected.

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


回答5:

cellForRowAtIndexPath will be repeatedly called when you are scrolling the tableView unless you have very few number of rows.