0

I have a UICollection which is implemented and works, however I cannot achieve the scrolling I want.

Here is a picture of my UICollectionView, I have resized the grey cell to 250 by 250.

enter image description here

My issue is, when I start scrolling, this is what happens.

My cell first starts off on the far left, but notice what happens if I start to scroll horizontally.

enter image description here

enter image description here

enter image description here

As you can see, the seam between the cells moves over to the left the more I scroll through the cells. This is not what I want.

What I want to achieve is: the cell is aligned to the center, and when you scroll, instead of the center of the cells moving to the left more and more, I want the cell to stay in the middle. Much like a PageViewController does except I want it to be UICollectionViewCells.

I have tried adding in the following code for example:

    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    float pageWidth = 210;

    float currentOffset = scrollView.contentOffset.x;
    float targetOffset = targetContentOffset->x;
    float newTargetOffset = 0;

    if (targetOffset > currentOffset)
        newTargetOffset = ceilf(currentOffset / pageWidth) * pageWidth;
    else
        newTargetOffset = floorf(currentOffset / pageWidth) * pageWidth;

    if (newTargetOffset < 0)
        newTargetOffset = 0;
    else if (newTargetOffset > scrollView.contentSize.width)
            newTargetOffset = scrollView.contentSize.width;

        targetContentOffset->x = currentOffset;
        [scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
    }

Which achieves the even scrolling, however I want to have paging enabled aswell as bounce.

enter image description here

Because if I enable paging and bounce, the scrolling is very smooth and elegant, however If I use the code up above the scrolling is very rugged and mechanical.

So How can I achieve even scrolling that is smooth like apples default scrolling, with my UICollectionViewCell being centred in the middle?

If I didn't explain the problem well enough, this post here explains my problem except I am using one cell instead of three, and I want the scrolling to be smooth and bounce etc.

Community
  • 1
  • 1
Josh
  • 745
  • 1
  • 7
  • 22

1 Answers1

0

I think this should work (disable paging):

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
  if (!decelerate) {
    // do your calculations
    [scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
  }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
  // do your calculations
  [scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
}
almas
  • 7,090
  • 7
  • 33
  • 49