簡體   English   中英

在UICollectionView中注冊多個單元格(swift 3)

[英]Registering multiple cells in UICollectionView (swift 3)

對於UICollectionViews ,是否可以有多個單元格類型?

例如:

media_cell

regular_cell

ad_cell

您是否只需要注冊它們,或者您是否必須包含if語句並根據某個變量更改布局以實現此效果。

例如:

if cell.ad == true {

}

原因是,我想要一個略有不同大小的單元格來存在圖像。 我想重新調整單元格可以工作,但我沒有在網上看到任何東西。

有什么建議

試試這個:1。注冊兩個(或更多)單元格。 2.為每個配置cellforItem。 3.為每個配置sizeForItem。 第一:

self.collectionView.register(SmallCell.self, forCellWithReuseIdentifier: "smallCell")
self.collectionView.register(BigCell.self, forCellWithReuseIdentifier: "bigCell")

然后:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     if dataSource[indexPath.item].hasImage {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “smallCell”, for: indexPath) as! SmallCell
        let model = dataSource[indexPath.item]
        cell.model = model
        return cell
      } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: “bigCell”, for: indexPath) as! BigCell
        let model = dataSource[indexPath.item]
        cell.model = model
        return cell
       }   
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     if dataSource[indexPath.item].hasImage {
        return CGSize(width: collectionView.frame.width, height: cellHeight+100)
     } else {   
        return CGSize(width: collectionView.frame.width, height: cellHeight)    
     }       
}

兩件事和一切應該是有效的:

  1. 您可以在一個集合視圖中注冊任意數量的單元格。
  2. 查看自行調整大小的主題,您不必擔心不同大小的單元格。

很棒的教程

更多信息在這里這個精彩的答案

祝好運 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM