在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. 查看自行resize的主题,您不必担心不同大小的单元格。

很棒的教程

更多信息在这里这个精彩的答案

祝你好运 :)