多數人學 iOS 時寫的第一個輪播圖,都是用 ScrollView 做的:在 ScrollView 上橫向排上一長串 ImageView,再靠 page 對齊做出逐頁滾動的效果。這在圖片數量少的時候沒問題,但廣告圖一多,就需要建立大量 ImageView,記憶體開銷跟著上去。
改用 CollectionView 就是另一回事了。這裡分享一個以 CollectionView 實作的輪播元件 KHAdView,程式碼已放在 GitHub 上,使用說明也有中英雙語版本,需要的朋友可以直接取用。
先來看成果。外觀上就是一般的輪播廣告圖,真正的重點都在程式碼裡,建議直接下載原始碼研究。

靠 UICollectionView 的 cell 複用機制,系統最多只需要建立兩個 CollectionViewCell,也就是最多兩個 ImageView。用兩個 ImageView 撐起無限張圖片的播放需求,記憶體佔用大幅下降。
可以同時採用 UICollectionViewDelegate 與 UIScrollViewDelegate,操作與事件監聽都更方便。
支援雙向循環滾動
可自訂廣告視圖外觀
同時支援網路 URL 與本地檔案
下載後把 KHAdView 資料夾內的原始碼複製到你的專案目錄。
初始化 KHAdView 並指定 Frame。
KHAdView *view = [[KHAdView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, KHAdView_Height)]; self.tableView.tableHeaderView = view;
當然,也可以用 Auto Layout 來決定大小與位置。
用 setDataSource: WithSourceType: 餵資料,並透過 SourceType 指定來源是 URL 還是本地檔案。
[self.khAdView setDataSource:_urlArr WithSourceType:KHSourceInternetType];
啟動計時器,讓輪播自動播放。
[self.khAdView startTimer];

調整顏色
底部背景列顏色,預設黑色
self.khAdView.bottomViewColor = [UIColor redColor];
PageControl 一般指示色,預設白色
self.khAdView.pageIndicatorTintColor = [UIColor yellowColor];
當前頁 PageControl 指示色,預設紅色
self.khAdView.currentPageIndicatorTintColor = [UIColor blackColor];
底部背景列高度,預設 30
self.khAdView.bottomViewHeight = 50;
底部背景列透明度,預設 0.3
self.khAdView.alpha = 1.0;
計時器間隔,預設 2 秒
self.khAdView.timeInterval = 1.f;
滾動方向,預設由右向左
self.khAdView.direction = KHScrollDirectionFromLeft;
隱藏底部背景列與頁碼指示器,預設不隱藏
self.khAdView.hideBottomView = YES; self.khAdView.hidePageControl = YES;
所謂循環,其實是一種視覺錯覺。假設有 A、B、C 三張圖,只要把頭尾各複製一張接到兩端,就形成 C A B C A 的序列。接著讓它沿著 A→B→C→A 的方向連續滾動,單一方向上的循環就成立了。
最後一步是關鍵:透過 scrollViewDidScroll 判斷目前顯示的是第幾張,如果滾到了第二張 A,就悄悄(不帶動畫)把 CollectionView 移回第一張 A,這一點最關鍵,也最需要小心處理。反方向的循環同理。核心程式碼如下:
- (void)setDataSource:(NSArray *)dataSource WithSourceType:(KHSourceType)sourceType{
_dataSource = dataSource;
self.images = [NSMutableArray array];
NSInteger count = dataSource.count + 2;
for (NSInteger i = 0; i < count; i++) {
UIImage *image = nil;
switch (sourceType) {
case KHSourceInternetType:
if (0 == i) {
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dataSource lastObject]]]];
} else if (count - 1 == i) {
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dataSource firstObject]]]];
} else {
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:dataSource[i - 1]]]];
}
[self.images addObject:image];
break;
default:
if (0 == i) {
image = [UIImage imageNamed:[dataSource lastObject]];
} else if (count - 1 == i) {
image = [UIImage imageNamed:[dataSource firstObject]];
} else {
image = [UIImage imageNamed:dataSource[i - 1]];
}
[self.images addObject:image];
break;
}
}
[self.collectionView reloadData];
}- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
NSInteger currentPage = (scrollView.contentOffset.x / CGRectGetWidth(self.frame)) - 1;
self.pageControl.currentPage = currentPage;
if (currentPage < 0) {
self.pageControl.currentPage = self.dataSource.count - 1;
[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.dataSource.count inSection:0]
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
animated:NO];
return;
} else if (currentPage == self.dataSource.count) {
self.pageControl.currentPage = 0;
[self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0]
atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
animated:NO];
return;
}
}文章只列出部分程式碼,有興趣的朋友歡迎到 GitHub 下載完整原始碼與 Demo。覺得好用可以直接 fork 進自己的專案,也歡迎給個 star。本人接觸 iOS 時間還不長,若程式碼有可改進之處,歡迎提出建議。
文章來自顾 Zhang 的投稿。