iosswiftuitableviewuitableviewautomaticdimension

Tableview scrollToRow(at:at:animated) causing scrollViewDidScroll(_) to be called multiple times


I have checked all possibilities as to why my UITableView is behaving so oddly for the whole day. Finally, right now I noticed something strange. I needed some help in figuring out if what I noticed is true or the problem could be in someplace else.

So in tableView(_:didSelectRowAt:), I want to scroll to a particular cell after resizing the heights of all the cells. (I am increasing the heights of all the cells.)

This is a small relevant part of my scrollViewDidScroll(_) method body that is responsible for deciding which part of the section of screen was tapped (I need this for some other stuff to work):

public func scrollViewDidScroll(_ scrollView: UIScrollView) {        
   let touchLocation = scrollView.panGestureRecognizer.location(in: containerView)
   let touchX = touchLocation.x
   print("X: \(touchX)")
  .
  .
  .
}

Now in my didSelectRowAt, when I call scrollToRow as:

tableView.scrollToRow(at: indexPath, at: .top, animated: false)

I get this as output:

X: 132.0 (old touch x)
X: 130.66665649414062 (old touch x when scrolling stopped)
X: 188.66665649414062 (new touch x of tap)
X: 188.66665649414062 (not sure why this was printed again)

But now when I execute the scrollToRow as:

tableView.scrollToRow(at: indexPath, at: .top, animated: true)

X: 160.3333282470703
X: 160.3333282470703 (new touch x of tap)
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
X: 177.66665649414062
.
.
.
174 times .
.
.
X: 177.66665649414062

This is very strange. Can someone explain why this could be happening?


Solution

  • scrollViewDidScroll gets called every frame that the scroll view has scrolled, doesn’t matter if it’s done by the user or by calling scrollTo methods. This can be up to, I think, 120 times per second while the user is scrolling.

    If you want to do something when the scroll view has stopped, you should use the didEndDeccelerating and didEndScrollingAnimation delegate methods.