做 iOS App 最常打交道的兩個元件大概就是 UITableView 和 UICollectionView。最近手上正在處理一個天氣預報專案,大量用到 UICollectionView,順便把知識梳理一遍。
從 iOS 6 開始才有 UICollectionView,它的 API 設計和 UITableView 幾乎如出一轍,同樣需要設定 dataSource 與 delegate,學過 table view 的人遷移成本很低。
要讓 collection view 跑起來,基本上得實作這三個協議。
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
// 高亮狀態
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,這兩個狀態分開設計就是為了這種情境。
// 每個 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 檔案設計 cell 有個前提:你必須真的透過它調整樣式。如果只是擺幾個預設元件,那麼在 storyboard 裡直接拉、或用純程式碼建立,反而更清楚。什麼時候該用 nib、什麼時候該在 storyboard 操作,這問題我自己也糾結了很久,目前的判斷是:cell 需要跨多個 collection view 重複使用、且樣式需要設計師反覆調整時,nib 才值得。