如何在 Swift 中使用 UICollectionView?


要在 Swift 中使用集合檢視,首先我們需建立一個集合檢視。我們可以將其拖放到情節提要中,也可以透過程式設計來建立它。然後,我們需要確認我們類與 UICollectionViewDataSource 和 UICollectionViewDelegate 一致。而且,如果我們需要自定義單元格大小和佈局,我們需要確認它與 UICollectionViewDelegateFlowLayout 一致。

我們來看看透過程式設計建立集合檢視所需步驟。

func initCollection() {
   let layout = UICollectionViewFlowLayout()
   layout.itemSize = CGSize(width: 50, height: 50)
   let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
   collection.dataSource = self
   collection.delegate = self
   collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
   collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
   self.view.addSubview(collection)
}

我們需要在 ViewDidLoad() 方法中呼叫上述函式。無論我們是透過程式設計還是透過情節提要建立集合,都需要分配資料來源,並委派給表提供資料,並分別觀察其行為。

現在,我們需要告訴集合,它應該有多少部分 −

func numberOfSections(in collectionView: UICollectionView) -> Int {
   return 1
}

然後,我們需要告訴它將有多少項,以及單元格中應該存在哪些資料。

func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return 7
}
func collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
   cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
   return cell
}

根據需要,我們還可以選擇性地為其賦予不同的尺寸。

func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
   let size = CGSize(width: 200, height: 50)
   return size
}

當我們在裝置上執行上述程式碼時,這就是產生的結果。

更新時間:2020 年 6 月 30 日

418 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告