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

UICollectionView 入門:三大協議與自訂 Cell

編輯:iOS 相關資訊

做 iOS App 最常打交道的兩個元件大概就是 UITableView 和 UICollectionView。最近手上正在處理一個天氣預報專案,大量用到 UICollectionView,順便把知識梳理一遍。

從 iOS 6 開始才有 UICollectionView,它的 API 設計和 UITableView 幾乎如出一轍,同樣需要設定 dataSource 與 delegate,學過 table view 的人遷移成本很低。

三個組成部分

  • Cell:真正顯示內容的資料單元。
  • Supplementary Views:頁眉與頁腳這類附屬視圖。
  • Decoration Views:純裝飾性的背景視圖。

需要實作的協議

要讓 collection view 跑起來,基本上得實作這三個協議。

UICollectionViewDataSource:提供資料

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int

func collectionView(collectionView: UICollectionView,
     numberOfItemsInSection section: Int) -> Int

func collectionView(collectionView: UICollectionView,
     cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell

UICollectionViewDelegate:處理互動

// 高亮狀態
optional func collectionView(collectionView: UICollectionView,
    shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool
optional func collectionView(collectionView: UICollectionView,
    didHighlightItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(collectionView: UICollectionView,
    didUnhighlightItemAtIndexPath indexPath: NSIndexPath)

// 選取狀態
optional func collectionView(collectionView: UICollectionView,
    shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool
optional func collectionView(collectionView: UICollectionView,
    didSelectItemAtIndexPath indexPath: NSIndexPath)
optional func collectionView(collectionView: UICollectionView,
    shouldDeselectItemAtIndexPath indexPath: NSIndexPath) -> Bool

這裡有個實務上的分辨方式:shouldHighlight 對應手指按下,shouldSelect 對應手指放開。拖曳捲動過程中會經過 highlight 但不會 select,這兩個狀態分開設計就是為了這種情境。

UICollectionViewDelegateFlowLayout:控制排版

// 每個 item 的尺寸
optional func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize

// 每個 section 的內距
optional func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    insetForSectionAtIndex section: Int) -> UIEdgeInsets

間距(minimumInteritemSpacing、minimumLineSpacing)則是設定在 UICollectionViewLayout 物件上,不在 delegate 方法裡。自訂排版時繼承 UICollectionViewLayout 並覆寫 layoutAttributesForElementsInRect: 是必經之路。

關於是否該用 nib

用 nib 檔案設計 cell 有個前提:你必須真的透過它調整樣式。如果只是擺幾個預設元件,那麼在 storyboard 裡直接拉、或用純程式碼建立,反而更清楚。什麼時候該用 nib、什麼時候該在 storyboard 操作,這問題我自己也糾結了很久,目前的判斷是:cell 需要跨多個 collection view 重複使用、且樣式需要設計師反覆調整時,nib 才值得。

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