da1lbi3 da1lbi3 - 14 days ago 5
Swift Question

UIScrollView setContentOffset not right

I have an UIScrollView with some labels inside. I can move the scroll view to the other 'page' with an button. But the offset isn't right when I push it too fast.

My code to move the scrollview to the next page:

@IBAction func moveToRight(_ sender: Any) {
let size = Int(scrView.contentOffset.x) + Int(scrView.frame.size.width);
scrView.setContentOffset(CGPoint(x: size, y: 0), animated: true)
}


The offset isn't right when I push it too fast. It looks like that the current animation stops and is going to perform the next one from it's current (unfinished) position.

Does anybody has an solution for this?

Answer

I don't have time to test but I think you are on the right track about the main reason of the issue. Since animated is set to true, my guess is contentOffset.x has not yet been set to its ultimate value until animation is finished.

Why don't you change your logic a bit and create a property which remembers the current page at where you last scrolled:

var currentPage: Int = 0

Then every time you moved right, increment the current page number if possible:

@IBAction func moveToRight(_ sender: Any) {
  let maxX = scrollView.contentSize.x - scrollView.frame.width
  let newX = CGFloat(currentPage + 1) * scrollView.frame.width
  if newX <= maxX {
    currentPage = currentPage + 1
    scrView.setContentOffset(CGPoint(x: newX, y: 0), animated: true)
  }
}