简体   繁体   English

在UICollectionView中注册多个单元格(swift 3)

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

For UICollectionViews , is it possible to have multiple cell types? 对于UICollectionViews ,是否可以有多个单元格类型?

For example: 例如:

media_cell

regular_cell

ad_cell

Would you just have to register them or do you have to include an if statement and change the layout according to some variable to achieve this effect. 您是否只需要注册它们,或者您是否必须包含if语句并根据某个变量更改布局以实现此效果。

For example: 例如:

if cell.ad == true {

}

The reason being, I want a slightly different sized cell for when an image is present. 原因是,我想要一个略有不同大小的单元格来存在图像。 I guess resizing the cell could work but I haven't seen anything on this online. 我想重新调整单元格可以工作,但我没有在网上看到任何东西。

Any suggestions 有什么建议

Try this: 1. Register two(or more) cells. 试试这个:1。注册两个(或更多)单元格。 2.Configure cellforItem for each. 2.为每个配置cellforItem。 3. Configure sizeForItem for each. 3.为每个配置sizeForItem。 First: 第一:

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

And then: 然后:

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)    
     }       
}

Two things and everything should be works: 两件事和一切应该是有效的:

  1. You can register any number of cells in one collection view. 您可以在一个集合视图中注册任意数量的单元格。
  2. Check out self-sizing cells topic and you should not worry about different sizes of cells. 查看自行调整大小的主题,您不必担心不同大小的单元格。

Great tutorial 很棒的教程

More info in this brilliant answer here 更多信息在这里这个精彩的答案

Good luck :) 祝好运 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM