iosipaduiscrollviewanimatedcontentoffset

UIScrollView setContentOffset scrolls outside the content size and doesn't snap in back


I want to scroll to the top of a UIScrollView. You have two possibilities:

If I use an animation then the scrollview sometimes scrolls to (0, -26) instead of (0, 0). So it scrolls further but then doesn't go back to (0, 0). This currently happens on iPad only.

If I don't use an animation this works everytime as expected. Has somebody a clue what is wrong here? I tested this on iPad 2 iOS 8.4 simulator

Edit:

Before I made my call with setContentOffset() I had this:

scrollView.layoutIfNeeded();
scrollView.setContentOffset(somePosition, true);

Removing layoutIfNeeded also removes the problem. But why?

Note: I wasn't calling setContentOffset() multiple times consecutively. That are completely different tasks!


Solution

  • Try it this way:

    scrollView.layoutIfNeeded();
    delay(0.05) {
        scrollView.setContentOffset(somePosition, true);
    }
    

    (where delay is here: dispatch_after - GCD in swift?)

    My idea is that this might give layout time to happen before we proceed.

    Another idea might be to try reversing the order of those two line:

    scrollView.setContentOffset(somePosition, true);
    scrollView.layoutIfNeeded();
    

    The idea here is that layout will take place during the animation, and we know that layout is designed to work during animation (that is why layout changes during rotation are animated, for example).