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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值