iOS 细节大集合爬坑日记

CollectionView水平滚动

2017-08-08  本文已影响641人  噬尾蛇

目的:为了实现CollectionView能够水平滚动并且每次只滚到下一个item上

步骤

创建一个CollectionView的视图

//懒加载
-(UICollectionView *)collection
{
    if (!_collection) {
        CGFloat itemWidth = kScreenPortraitWidth - 56;
        CGFloat itemHeight= itemWidth / 318 * 170 + (251 - 170);
        UICollectionViewFlowLayout *layout = [[CollectionFlowLayout alloc]init];
        //滚动方向->水平
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        //间距
        layout.minimumLineSpacing = 12;
        layout.minimumInteritemSpacing = 12;
        //每个item的size
        layout.itemSize = CGSizeMake(itemWidth, itemHeight);
        
        _collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
        _collection.delegate = self;
        _collection.dataSource = self;
        _collection.scrollsToTop = NO;//滚动到顶部->NO
        _collection.showsHorizontalScrollIndicator = NO;//显示水平滚动条->NO
        //滚动的时候快速衰弱
        _collection.decelerationRate = UIScrollViewDecelerationRateFast;
       //_collection.pagingEnabled = YES;//若是整页滚动,则使用
        [_collection registerClass:[BannerCollectionViewCell class] forCellWithReuseIdentifier:kCollectionCell];
    }
    return _collection;
}

delegate和dataSource方法

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{    //将要停止前的坐标
    
    CGFloat velocityFloat = velocity.x;
    CGFloat screenFloat = self.bounds.size.width/2;
    CGFloat currentCenter = screenFloat-scrollView.contentOffset.x;//当前中心点偏移
    
    CGPoint currentPoint = [self convertPoint:self.collection.center toView:self.collection];
    NSIndexPath *idxPath = [self.collection indexPathForItemAtPoint:currentPoint];
    
    CGFloat collectionWidth = self.bounds.size.width - 16 - 29;
    CGFloat nextX = idxPath.row*collectionWidth;
    
    if (velocityFloat > 0 || velocityFloat < 0) {
        targetContentOffset->x = nextX;
        targetContentOffset->y = 0;
    }else{
        targetContentOffset->x = targetContentOffset->x;
        targetContentOffset->y = 0;
    }
}

Banner.gif

如果是全屏的item则可以在初始化CollectionView的时候使用

CollectionView.pagingEnabled = YES;
上一篇 下一篇

猜你喜欢

热点阅读