iOS开发中利用UICollectionView创建文字轮播控件

背景:

公司项目中有一个需求:在首页上添加一个纵向滚动的文字轮播广告。

效果图:
这里写图片描述

轮播效果图
实现过程:

  1. 上网搜索相关demo

  2. 搜到一个demo,demo是利用UIScrollView实现的

  3. 思考:既然能用UIScrollView实现为什么不用UITableView去实现呢?使用UITableView就不用考虑复用以及调整scrollView上子控件位置的问题了。

  4. 手动敲代码利用UITableView实现具有需求效果的控件,可当UITableView滑动到最后一个cell再滑动到第一个cell的时候出现问题(并不能很流畅地从最后一个cell滑动回第一个cell)。

  5. 网上再搜索相关demo,发现了利用UICollectionView实现该效果的一个demo。发现此demo的效果很好、代码易于理解、可扩展性高。

  6. 自己手动敲一个demo实现需求的效果。

手动敲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返回数。

  • (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return scrollMaxSections;

}
最终实现效果:

这里写图片描述

最终效果图
demo地址:https://gitee.com/liangsenliangsen/uicollectionview_text_carousel

本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。

猜你喜欢

转载自blog.csdn.net/u010105969/article/details/79912517