您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

UIPageControl 分頁控件使用小結:屬性、事件與自定義配色

編輯:iOS 相關教學

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」的文字指示器。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved