背景:
公司項目中有一個需求:在首頁上添加一個縱向滾動的文字輪播廣告。
效果圖:

實現(xiàn)過程:
1. 上網(wǎng)搜索相關(guān)demo
2. 搜到一個demo,demo是利用UIScrollView實現(xiàn)的
3. 思考:既然能用UIScrollView實現(xiàn)為什么不用UITableView去實現(xiàn)呢?使用UITableView就不用考慮復(fù)用以及調(diào)整scrollView上子控件位置的問題了。
4. 手動敲代碼利用UITableView實現(xiàn)具有需求效果的控件,可當(dāng)UITableView滑動到最后一個cell再滑動到第一個cell的時候出現(xiàn)問題(并不能很流暢地從最后一個cell滑動回第一個cell)。
5. 網(wǎng)上再搜索相關(guān)demo,發(fā)現(xiàn)了利用UICollectionView實現(xiàn)該效果的一個demo。發(fā)現(xiàn)此demo的效果很好、代碼易于理解、可擴(kuò)展性高。
6. 自己手動敲一個demo實現(xiàn)需求的效果。
手動敲demo:
先在當(dāng)前控制器的view上添加一個UICollectionView,每個item的大小等于UICollectionView的大小。再添加一個定時器,每隔一定的時間讓UICollectionView進(jìn)行滾動。
滾動代碼:
// 1、當(dāng)前正在展示的位置
? ? NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
//? ? NSLog(@"current:%lu", currentIndexPath.row);
? ? // 馬上顯示回最中間那組的數(shù)據(jù)
? ? 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是一個數(shù)值較大的section返回數(shù)。
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
? ? return scrollMaxSections;
}
最終實現(xiàn)效果:

demo地址:https://gitee.com/liangsenliangsen/uicollectionview_text_carousel
本篇文章到這里就結(jié)束了,愿大家加班不多工資多,男同胞都有女朋友,女同胞都有男朋友。??