CollectionView 单个选项卡的滑动

2,244 阅读1分钟

前言

最近在做一个旅行类的项目,里面哟孤儿横向滑动的选项卡功能,乍一看设计图,感觉很简单。横向滑动,CollectionView的flowLayout有这个设置属性,分分钟搞定。后来需求要每次滑动一个选项卡。这就让我有点棘手了,因为心里知道这个应该是要自己去计算偏移量的问题了

正题

实现这个功能,主要就是调用了一个UIScrollView的代理方法- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset

不说别的了,直接上代码

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    float pageWidth = 200 + 10;
    float currentOffset = _collectionView.contentOffset.x;
    float targetOffset = targetContentOffset->x;
    float newTargetOffset = 0;
    if (targetOffset+ 20  > currentOffset) {
        newTargetOffset = ceilf(currentOffset/pageWidth) * pageWidth;
    }else{
        newTargetOffset = floorf(currentOffset/ pageWidth) * pageWidth;
    }
    if (newTargetOffset < 0) {
        newTargetOffset = 0;
    }else if (ABS(scrollView.contentSize.width - (newTargetOffset + pageWidth))< pageWidth){
        newTargetOffset = scrollView.contentSize.width - _collectionView.bounds.size.width ;
    }
    newTargetOffset = ceilf(newTargetOffset);
    targetContentOffset->x = currentOffset;
    [scrollView setContentOffset:CGPointMake(newTargetOffset, 0) animated:YES];
}

这里面pageWidth的值是一个item的宽度加间距,之后对于滑到最后一个item的时候不足一个item的宽度做了相应的处理。

如果你们的设计是两边都有留白的情况,你可以设置flowLayout.sectionInset,相应的collectionViewcontentInset属性也要做相应的处理

OS:

大神们有什么好的建议多给我提出来

传送门

Demo