UICollectionView horizontal paging with 3 items

前端 未结 6 1309
眼角桃花
眼角桃花 2020-12-04 06:21

I need to show 3 items in a UICollectionView, with paging enabled like this

\"enter

6条回答
  •  被撕碎了的回忆
    2020-12-04 06:50

    you will have to override targetContentOffsetForProposedContentOffset:withScrollingVelocity: method of the flow layout. This way you snap the stopping point of the scrollview.

    -(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
    {
        CGFloat yOffset = MAXFLOAT;
    
        CGRect proposedRect;
        proposedRect.origin = proposedContentOffset;
        proposedRect.size = self.collectionView.bounds.size;
        CGPoint proposedCenterPoint = CGPointMake(CGRectGetMidX(proposedRect), CGRectGetMidY(proposedRect)) ;
    
        NSArray *array = [super layoutAttributesForElementsInRect:proposedRect];
    
        for (UICollectionViewLayoutAttributes *attributes in array)
        {
            CGFloat newOffset = attributes.center.y - proposedCenterPoint.y;
            if ( fabsf(newOffset) < fabs(yOffset))
            {
                yOffset = newOffset;
            }
        }
    
        return CGPointMake(proposedContentOffset.x, proposedContentOffset.y + yOffset);
    }
    

    Also you will beed to set the sectionInset of the flow layout to center the first cell and the last cell. My example is the height but easy to switch to width.

    CGFloat height = (self.collectionView.bounds.size.height / 2.0 ) - (self.itemSize.height / 2.0) ;
    self.sectionInset = UIEdgeInsetsMake(height, 30.0, height, 30.0) ;
    

提交回复
热议问题