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

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

问题描述

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

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

例如:

media_cell

media_cell

regular_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 {

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天全站免登陆