UIScrollView does not always animate deceleration when overriding scrollViewWillEndDragging
Asked Answered
R

1

7

Here is my override code - it just calculates where to snap to:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

    if(targetContentOffset->y < 400) {
        targetContentOffset->y = 0;
        return;
    }

    int baseCheck = 400;

    while(baseCheck <= 10000) {
        if(targetContentOffset->y > baseCheck && targetContentOffset->y < baseCheck + 800) {
            targetContentOffset->y = (baseCheck + 340);
            return;
        }
        baseCheck += 800;
    }

    targetContentOffset->y = 0;
}

When I hold my finger down for more than a second or two to drag the scrollview and then lift my finger, it usually animates into place. However, when I do a quick "flick" it rarely animates - it just snaps to the targetContentOffset. I am trying to emulate default paging behavior (except trying to snap to custom positions).

Any ideas?

Resection answered 6/3, 2013 at 14:38 Comment(0)
R
6

I ended up having to animate it manually. In the same function, I set the targetContentOffset to where the user left off (current contentOffset) so that it doesnt trigger it's own animation, and then I set the contentoffset to my calculation. Additionally, I added in a velocity check to trigger'automatic' page changes. It's not perfect, but hopefully it will help other with the same issue.

(I modified the above function for readability since no one needs to see my calculations)

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {

    CGPoint newOffset = CGPointMake(targetContentOffset->x, targetContentOffset->y);
    *targetContentOffset = CGPointMake([broadsheetCollectionView contentOffset].x, [broadsheetCollectionView contentOffset].y);

    if(velocity.y > 1.4) {
        newOffset.y += pixelAmountThatWillMakeSurePageChanges;
    }
    if(velocity.y < -1.4) {
        newOffset.y -= pixelAmountThatWillMakeSurePageChanges;
    }

    // calculate newoffset

    newOffset.y = calculatedOffset;
    [scrollView setContentOffset:newOffset animated:YES];
}
Resection answered 6/3, 2013 at 18:5 Comment(2)
I tried this with a horizontal UICollectionView, and while it worked, the resulting animation was jittery; I think there were two animations going on at the same time. Wrapping setContentOffset: in dispatch_async fixed it.Credible
Did you ever make it 'perfect' way?Uganda

© 2022 - 2024 — McMap. All rights reserved.