照片牆 (Grid Photo Wall)

CollectionViewController, CollectionViewCell, FlowLayout

--

成品:照片牆就是要用這種主題才美呀~時間又花在選圖排序上 😅

▲本想配合 IG API 作業練習,每個圖都開分頁來看卻都不夠美不想用…
▲只好去官網找圖,直圖且不同展的數量不多,全點開來看一晚就過了
▲最後仍需用橫圖湊量,不過結果算挺不錯的啦!Ya~
▲為了名稱好辨別全改 TeamLab,原為 teamLab★
▲參考來源:彼得

前置作業

▲加 CollectionViewController 並設為首頁 + Navigation
▲新增 Cocoa Touch Class * 3,取名後各自配好,別忘了 Cell ID 也要
▲ ImageView (Aspect Fill) 入 Cell 小框,且 AutoLayout 上下左右設為 0
▲ Cell 拉 Segue 至 PhotoViewController ,ImageView 也加上去
▲ TeamLabCollectionViewController — ControllerView
➞ Estimate Size 選 None 便不會自動計算高度
➞ Layout 選 Flow 則為 1 格 1 格 照片牆模式

TeamLabCollectionViewCell.swift:ImageView 拉 Outlet

TeamLabCollectionViewController.swift

刪除紅框處

▲我們只要 1 個 Section 預設也為 1 個,這 4 行便可安心刪除

▲ item 有 27 個

▲和 TableView 作法一樣,轉型成 Cell
▲ TableView 為 indexPath.row,這為 indexPath.item

▲設定 1 排固定照片數量的 cell 大小:更多方法請參考彼得教學
➞ itemSpace:間距大小,columnCount:1 排幾個項目
➞ collectionViewLayout 是 CollectionViewController 的變數
➞ collectionViewLayout 型別為 UICollectionViewLayout 所以要轉型
➞計算 cell 寬度
◇ floor 為無條件捨去,避免超出螢幕
◇ collectionView.bounds.width 是螢幕寬度,此案 SE1 為 320
➞ itemSize 設為正方形
➞用自己尺寸來設非 AutoLayout 所以 estimatedItemSize = .zero
➞將 Min Spacing For Cells & Min Spacing For Lines 都設為 itemSpace

PhotoViewController.swift

▲定義 init,由參數設定 property;拉 Outlet;設圖片

回 TeamLabCollectionViewController.swift:拉 SegueAction

▲本來寫不出來,看彼得範例才學到
➞ tableView 是 tableView.indexPathForSelectedRow?.row
➞這是 collectionView.indexPathsForSelectedItems?.first?.item

完整程式碼:TeamLabCollectionViewController

TeamLabCollectionViewCell,PhotoViewController

--

--