前言
最近公司项目设计了一个滚动,有着特定的距离,实现效果如下:
先上UICollectionView的代码:
- (UICollectionView*)collectionView{
if(_collectionView==nil){
UICollectionViewFlowLayout*layout = [UICollectionViewFlowLayoutnew];
layout.itemSize=CGSizeMake(KCellWidth,KCellHeight);
layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
layout.minimumLineSpacing=2;
_collectionView= [[UICollectionViewalloc]initWithFrame:CGRectMake(0,200,ScreenWidth,KCellHeight)collectionViewLayout:layout];
_collectionView.backgroundColor= [UIColorwhiteColor];
_collectionView.delegate=self;
_collectionView.dataSource=self;
_collectionView.scrollsToTop=NO;
_collectionView.showsVerticalScrollIndicator=NO;
_collectionView.showsHorizontalScrollIndicator=NO;
_collectionView.pagingEnabled=YES;
[_collectionViewregisterClass:[UICollectionViewCellclass]forCellWithReuseIdentifier:KCellID];
}
return_collectionView;
}
主要代码:
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView{
_offer= scrollView.contentOffset.x;
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView*)scrollView{
if(fabs(scrollView.contentOffset.x-_offer) >10) {
if(scrollView.contentOffset.x>_offer) {
inti = scrollView.contentOffset.x/([UIScreenmainScreen].bounds.size.width-KCellSpace/2)+1;
NSIndexPath* index =[NSIndexPathindexPathForRow:iinSection:0];
[_collectionViewscrollToItemAtIndexPath:indexatScrollPosition:UICollectionViewScrollPositionCenteredHorizontallyanimated:YES];
}else{
inti = scrollView.contentOffset.x/([UIScreenmainScreen].bounds.size.width-KCellSpace/2)+1;
NSIndexPath* index =[NSIndexPathindexPathForRow:i-1inSection:0];
[_collectionViewscrollToItemAtIndexPath:indexatScrollPosition:UICollectionViewScrollPositionCenteredHorizontallyanimated:YES];
}
}
}
- (void)scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inoutCGPoint*)targetContentOffset{
if(fabs(scrollView.contentOffset.x-_offer) >20) {
if(scrollView.contentOffset.x>_offer) {
inti = scrollView.contentOffset.x/([UIScreenmainScreen].bounds.size.width-KCellSpace/2)+1;
NSIndexPath* index =[NSIndexPathindexPathForRow:iinSection:0];
[_collectionViewscrollToItemAtIndexPath:indexatScrollPosition:UICollectionViewScrollPositionCenteredHorizontallyanimated:YES];
}else{
inti = scrollView.contentOffset.x/([UIScreenmainScreen].bounds.size.width-KCellSpace/2)+1;
i = (i -1)<0?0:(i -1);
NSIndexPath* index =[NSIndexPathindexPathForRow:iinSection:0];
[_collectionViewscrollToItemAtIndexPath:indexatScrollPosition:UICollectionViewScrollPositionCenteredHorizontallyanimated:YES];
}
}
}
效果如下: