How to make a UIScrollView snap to icons (like App Store: Feature)

后端 未结 4 1685
渐次进展
渐次进展 2020-12-24 10:14

What I want to get is the same behaviour that this scroll view has:

\"App

4条回答
  •  一个人的身影
    2020-12-24 10:26

    You can either turn on pagingEnabled, or use decelerationRate = UIScrollViewDecelerationRateFast combined with scrollViewDidEndDragging and scrollViewDidEndDecelerating (which will minimize the effect of slowing scrolling to one location and then animating again to another location). It's probably not precisely what you want, but it's pretty close. And by using animateWithDuration it avoids the instantaneous jumping of that final snap.

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

    You can then write a snapScrollView, such as:

    - (void)snapScrollView:(UIScrollView *)scrollView
    {
        CGPoint offset = scrollView.contentOffset;
    
        if ((offset.x + scrollView.frame.size.width) >= scrollView.contentSize.width)
        {
            // no snap needed ... we're at the end of the scrollview
            return;
        }
    
        // calculate where you want it to snap to
    
        offset.x = floorf(offset.x / kIconOffset + 0.5) * kIconOffset;
    
        // now snap it to there
    
        [UIView animateWithDuration:0.1
                         animations:^{
                             scrollView.contentOffset = offset;
                         }];
    }
    

提交回复
热议问题