How can I prevent jerky scrolling of UIScrollView

2019-08-30 08:01发布

I have to update text of a label every time I scroll the UIScrollView...or everytime I scroll and leave it stop at a point on it's own. This updation of the text of the label is done based on the contentoffset of the scrollview. So now I am putting checks in each method :

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
     int one = scrollView.contentOffset.x/21;
     int two = (21*one)+14;
     CGPoint point = CGPointMake(two, scrollView.contentOffset.y);
     [scrollView setContentOffset:point animated:YES];
     [self setLabelText:@"scroll"];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    int one = scrollView.contentOffset.x/21;
    int two = (21*one)+14;
    CGPoint point = CGPointMake(two, scrollView.contentOffset.y);
    [scrollView setContentOffset:point animated:YES];
    [self setLabelText:@"scroll"];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint offset = scrollView.contentOffset;
    if (offset.x < minuteScrollMinX) offset.x = minuteScrollMinX;
    if (offset.x > minuteScrollMaxX) offset.x = minuteScrollMaxX;
    scrollView.contentOffset = offset;
}

Now after this, my scrollview becomes too jerky, how can I prevent this jerky scrolling of the scrollview? Is there a common delegate instead of these three methods or even the top two methods? Thanks in advance for any help.

1条回答
混吃等死
2楼-- · 2019-08-30 08:11

The calculations here shouldn't mess up your scrolling. The trouble is caused by a conflict between the top two methods:

 - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;

You need to check the willDecelarate argument in the first method. If it is true, do nothing - scrollViewDidEndDecelerating will get called eventually. If it is false, do the calc here. When willDecelarate is true you are calling your calculation from both methods, which messes up the scroll.

As the calulations are the same in both cases, you can also factor them out to a common method.

    - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
         [self calculateScrollOffset];
    }

    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView 
                      willDecelerate:(BOOL)decelerate
    {
        if (!decelerate) {
             [self calculateScrollOffset];
             }
    }


- (void) calculateScrollOffset
{
    int one = scrollView.contentOffset.x/21;
     int two = (21*one)+14;
     CGPoint point = CGPointMake(two, scrollView.contentOffset.y);
     [scrollView setContentOffset:point animated:YES];
     [self setLabelText:@"scroll"];
}
查看更多
登录 后发表回答