最近在琢磨遊戲關卡目錄頁的排版怎麼做,順手用 UICollectionView 寫了個小 demo,把最基礎的流程記錄下來。
在 Storyboard 對應的 ViewController 上拉一個 Collection View,然後在裡面放一個 Collection View Cell,Cell 裡再擺一個 Label。接著把這個 Cell 的 Reuse Identifier 命名為 defaultCell,UI 層的設定就完成了。
① UICollectionViewDataSource:負責提供畫面所需的資料,例如每一區有幾筆、每個位置要用什麼 Cell。
② UICollectionViewDelegate:負責處理使用者互動,例如點選了哪一格。
class MyCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var cv: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
cv.dataSource = self
cv.delegate = self
}
// 回報筆數
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
// 回報每一格的內容
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = cv.dequeueReusableCell(withReuseIdentifier: "defaultCell", for: indexPath) as! MyColletionCell
cell.label.text = "\(indexPath.section):\(indexPath.row)"
return cell
}
// 點選事件
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 在這裡處理被選中的 Cell
}
}
三個方法各司其職:一個決定數量,一個決定外觀,一個決定行為。跑起來就能看到 100 格依序排列的畫面。
小提醒:取出 Cell 時務必確認 Reuse Identifier 與 Storyboard 上填的字串完全一致,否則會在執行期拋出例外。另外原始碼中的 API 拼寫屬於舊版 Swift,若使用 Swift 3 以後的版本,請對照新版簽名調整。