需求是 app 首页 banner 图
1,循环滑动
2,左右翻页
3,自动滑动
原理:
用的是一个 UICollectionView 实现
1,把数据源扩大 (2倍 + 1)
- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
// self.datas.count * 2 防止 第一个往左轮播时数组越界
// self.datas.count * 2 + 1 防止 最后一个往右轮播时数组越界
return self.datas.count * 2 + 1;
}
2,将要停止拖拽时
- (void)scrollViewWillEndDragging:(UIScrollView*)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inoutCGPoint*)targetContentOffset
{
CGPoint target = [self nearestTargetOffsetForOffset:*targetContentOffset];
targetContentOffset->x= target.x;
targetContentOffset->y= target.y;
}
- (CGPoint)nearestTargetOffsetForOffset:(CGPoint)offset
{
CGFloat pageSize = self.collectionView.frame.size.width;
CGFloatpreFixSize = pageSize - (CGRectGetWidth(self.collectionView.frame) - pageSize) /2;
NSIntegerpage =round((offset.x- preFixSize)/ pageSize);
CGFloattargetX = page * pageSize;
returnCGPointMake(targetX + preFixSize, offset.y);
}
3,停止拖拽时和停止动画时
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView*)scrollView
{
[self scrollToNextDone];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView
{
[self scrollToNextDone];
}
- (void)scrollToNextDone
{
[self stopTimer];
[self startTimer];
CGPoint center = CGPointMake(self.collectionView.contentOffset.x + self.collectionView.center.x, self.collectionView.center.y);
NSIndexPath *nowIndexPath = [self.collectionView indexPathForItemAtPoint:center];
if(nowIndexPath &&self.datas.count!=0) {
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:(nowIndexPath.item % self.datas.count + self.datas.count) inSection:0];
// 取 self.datas.count + (1~~~ self.datas.count-1)
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}
}