UIPageControl 是大多數 iOS 教學不會細講的系統自帶控件。它的主要功能是實現視圖分頁,概念上有點類似網頁上的分頁指示器——就是畫面下方那一排小圓點。搭配 UIScrollView,就能做出一個帶自動輪播的橫向相簿。
先來看成品:

圖中紅框處便是 UIPageControl 的呈現樣式。
先在檔案頂部定義一個常量:
#define PAGENUM 4@property (strong, nonatomic) IBOutlet UIPageControl *page;
@property (strong, nonatomic) IBOutlet UIScrollView *imageScrollView;@synthesize page;
@synthesize imageScrollView;(void)viewDidLoad
{
[super viewDidLoad];
// 設定滾動視圖的內容尺寸、是否支持翻頁、是否顯示水平捲動標示、委派對象
imageScrollView.contentSize = CGSizeMake(PAGENUM * 320.0f,
imageScrollView.frame.size.height);
imageScrollView.pagingEnabled = YES;
imageScrollView.showsHorizontalScrollIndicator = NO;
imageScrollView.delegate = self;
// 為滾動視圖添加子視圖
// 這裡的子視圖用 UIButton,方便後續加上點擊操作
for (int i = 0; i < PAGENUM; i++) {
NSString *fileName = [NSString stringWithFormat:@"%d.jpg", i + 1];
UIButton *imageButton = [[UIButton alloc]
initWithFrame:CGRectMake(i * 320.0f, 0.0f, 320.0f, 218.0f)];
[imageButton setBackgroundImage:[UIImage imageNamed:fileName]
forState:UIControlStateNormal];
imageButton.tag = 900 + i;
[imageScrollView addSubview:imageButton];
}
// 設定 PageControl:總頁數、當前頁、值變化時要觸發的動作
page.numberOfPages = PAGENUM;
page.currentPage = 0;
[page addTarget:self
action:@selector(pageTurn:)
forControlEvents:UIControlEventValueChanged];
// 用 NSTimer 實現定時自動滾動
timeCount = 0;
[NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:@selector(scrollTimer)
userInfo:nil
repeats:YES];
}這裡有兩個關鍵設定值得說明。pagingEnabled = YES 讓 scrollView 自動吸附到「一頁」的寬度,使用者隨便一滑就會對齊,不必自己計算落點。contentSize 設為「頁數 × 單頁寬度」,是讓 scrollView 知道總共有多少可捲動的範圍。
另外,每個 imageButton 的 x 座標是 i * 320.0f,也就是把每張圖片依序排成橫向的一長條;tag 從 900 起算,是為了後續辨識點了哪一張。
// 滾圖的動畫效果
-(void)pageTurn:(UIPageControl *)aPageControl{
int whichPage = aPageControl.currentPage;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[imageScrollView setContentOffset:CGPointMake(320.0f * whichPage, 0.0f)
animated:YES];
[UIView commitAnimations];
}點一下 UIPageControl 的圓點,就透過 setContentOffset:animated: 把 scrollView 捲到對應頁面。
// 定時滾動
-(void)scrollTimer{
timeCount++;
if (timeCount == PAGENUM) {
timeCount = 0;
}
[imageScrollView scrollRectToVisible:CGRectMake(timeCount * 320.0, 65.0, 320.0, 218.0)
animated:YES];
}每 5 秒把 timeCount 加一,到最後一頁後歸零回到第一頁,形成循環。
上面的程式碼能跑,但有一個明顯的缺口:使用者手動滑動時,page 的 currentPoint 不會跟著更新。結果就是畫面已經換頁,下方的圓點卻還停在原處。
補法是實作 scrollView 的 delegate 方法:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
int pageIndex = scrollView.contentOffset.x / self.view.frame.size.width;
page.currentPage = pageIndex;
}另外還有兩處實務上必須處理:一是 NSTimer 會強引用 target,若在 dealloc 中沒有 invalidate,controller 永遠不會被釋放;二是使用者手動滑動時,最好暫停自動輪播,滑完幾秒後再恢復,否則會有種畫面被搶走的煩躁感。
這份範例到處出現 320.0f 與 218.0f,是 iPhone 5 之前 320pt 寬螢幕的時代產物。在現代專案中,這些數字應該全部改為從實際尺寸取得,例如:
CGFloat pageWidth = self.view.bounds.size.width;
imageScrollView.contentSize = CGSizeMake(PAGENUM * pageWidth,
imageScrollView.frame.size.height);並在旋轉或尺寸變更時重新計算。這樣才能同時支援各種螢幕與橫向旋轉。