版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337674
背景:
公司项目中有一个需求:在首页上添加一个纵向滚动的文字轮播广告。
效果图:
轮播效果图
实现过程:
手动敲demo:
先在当前控制器的view上添加一个UICollectionView,每个item的大小等于UICollectionView的大小。再添加一个定时器,每隔一定的时间让UICollectionView进行滚动。
滚动代码:
// 1、当前正在展示的位置
NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
// NSLog(@"current:%lu", currentIndexPath.row);
// 马上显示回最中间那组的数据
NSIndexPath *resetCurrentIndexPath = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:0.5 * scrollMaxSections];
[self.collectionView scrollToItemAtIndexPath:resetCurrentIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
// 2、计算出下一个需要展示的位置
NSInteger nextItem = resetCurrentIndexPath.item + 1;
NSInteger nextSection = resetCurrentIndexPath.section;
if (nextItem == 5) {
nextItem = 0;
nextSection++;
}
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
// NSLog(@”next:%lu”, nextIndexPath.row);
// 3、通过动画滚动到下一个位置
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
注意:scrollMaxSections是一个数值较大的section返回数。
}
最终实现效果:
最终效果图
demo地址:https://gitee.com/liangsenliangsen/uicollectionview_text_carousel
本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。