UIPageControl 是一排小圓點,用來指示「當前在第幾頁、總共幾頁」。它常被用來替代導航欄,配合手勢直接翻頁。最典型的例子就是 iPhone 主屏幕:圖標過多時自動分頁,底部的小圓點會隨著左右滑動即時更新。
UIPageControl *myPageControl =
[[UIPageControl alloc] initWithFrame:CGRectMake(0.0, 400.0, 320.0, 0.0)];
myPageControl.numberOfPages = 5; // 圓點總數
myPageControl.currentPage = 3; // 當前頁,索引從 0 開始
myPageControl.hidesForSinglePage = YES; // 只有一頁時不顯示圓點
myPageControl.defersCurrentPageDisplay = YES;
// 合適的時機手動刷新
[myPageControl updateCurrentPageDisplay];
這個屬性在「翻頁動畫尚未結束、業務數據還沒就位」時很有用:先把 currentPage 改對,但界面上的高亮留到動畫完成後再切換,避免圓點與內容不同步。
[self.view addSubview:myPageControl];
- (void)pageChanged:(id)sender {
UIPageControl *control = (UIPageControl *)sender;
NSInteger page = control.currentPage;
// 在這裡響應翻頁
}
[myPageControl addTarget:self
action:@selector(pageChanged:)
forControlEvents:UIControlEventValueChanged];
UIPageControl *page = [[UIPageControl alloc]
initWithFrame:CGRectMake(0, self.view.bounds.size.height - 50,
self.view.bounds.size.width, 50)];
page.backgroundColor = [UIColor clearColor]; // 背景透明
page.numberOfPages = 15; // 圓點個數
page.pageIndicatorTintColor = [UIColor orangeColor]; // 未選中圓點顏色
page.currentPageIndicatorTintColor = [UIColor redColor]; // 當前圓點顏色
page.currentPage = 1; // 當前頁
[page addTarget:self action:@selector(pageClick:) forControlEvents:UIControlEventValueChanged];
UIPageControl 本身只負責「顯示」,不負責「滾動」。它必須與 UIScrollView 協同工作:在 scrollViewDidScroll: 中根據 contentOffset 反算頁碼並賦給 currentPage,同時在 pageChanged: 中調用 setContentOffset:animated: 完成跳轉。雙向同步做好,圓點才會既跟手又能點擊。
另外要提醒的是,pageIndicatorTintColor 與 currentPageIndicatorTintColor 是 iOS 5 之後加入的屬性,它們大幅簡化了換膚工作,早期需要靠替換 drawRect 或塞入自定義子視圖的做法已經沒有必要。當頁數較多(例如超過 20 頁)時,圓點會擠在一起難以辨識,此時更合適的方案是換用 UIPageControl 的替代設計,例如顯示「3 / 20」的文字指示器。