在 UICollectionView 中注册多个单元格(swift 3) [英] Registering multiple cells in UICollectionView (swift 3)

查看:34
本文介绍了在 UICollectionView 中注册多个单元格(swift 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于UICollectionViews,是否可以有多种单元格类型?

For UICollectionViews, is it possible to have multiple cell types?

例如:

media_cell

regular_cell

ad_cell

您是只需要注册它们还是必须包含一个 if 语句并根据一些变量更改布局以实现此效果.

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 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.

任何建议

推荐答案

试试这个:1.注册两个(或更多)细胞.2.为每个配置cellforItem.3. 为每个配置 sizeForItem.第一:

Try this: 1. Register two(or more) cells. 2.Configure cellforItem for each. 3. Configure sizeForItem for each. First:

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

这篇关于在 UICollectionView 中注册多个单元格(swift 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆