在 iOS 中實作輪播圖,常見且穩定的做法是使用 UIScrollView 的分頁能力,搭配左、中、右三個視圖進行循環切換。當使用者滑到目前頁面的左側或右側時,系統會立即把即將顯示的內容更新到相應位置,再將 scrollView 的偏移量復位到中間頁,讓使用者感覺像是可以無限循環。

UIScrollView *scrollView = [[UIScrollView alloc] init]; scrollView.frame = CGRectMake(0, 0, kWidth, kHeight); scrollView.contentSize = CGSizeMake(kWidth * 3, kHeight); scrollView.pagingEnabled = YES; scrollView.showsHorizontalScrollIndicator = NO; scrollView.showsVerticalScrollIndicator = NO; [scrollView setContentOffset:CGPointMake(kWidth, 0)];
- (void)nextPage {
[_scrollView setContentOffset:CGPointMake(kWidth * 2, 0) animated:YES];
_currentIndex = (_currentIndex + 1) % _totalCount;
_currentView.backgroundColor = _colorArray[_currentIndex];
_pageControl.currentPage = _currentIndex;
[_scrollView setContentOffset:CGPointMake(kWidth, 0) animated:NO];
}
自動輪播雖然方便,但如果使用者正在手動操作,計時器就應該先停止,避免畫面突然跳動。實作時可以在 scrollViewWillBeginDragging 中取消 timer,在 scrollViewDidEndDecelerating 中重新啟動,並根據目前偏移量判斷使用者是向左還是向右滑動。
此外,若頁面數量較多,不建議一次建立所有內容視圖。可以只保留目前頁、前一頁與後一頁,並在每次切換時更新這三個視圖的內容,以降低記憶體使用量。