单个 UICollectionView 的多个单元格 [英] Multiple cells for a single UICollectionView

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

问题描述

在我的集合视图中,对于数组中不同类型的数据,单元格类必须具有完全不同的外观.

In my collection view, the cell class must have completely different appearance for different kinds of data in the array.

我正在寻找一种方法来创建多个单元格并根据输入数据选择不同的单元格,例如:

I am looking for a way to create multiple cells and choose a different one according to the input data, so for example :

internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell1 = collectionView.dequeueReusableCell..  as! kind1
    let cell2 = collectionView.dequeueReusableCell.. as! kind2
   // here choose a different one for each kind of data
    return cell1
}

我想了解是否:

  1. 如何做到这一点以及它在内存方面的方法是否正确?
  2. 这是一个好的设计吗?您将如何制作一个完全不同的单个单元格布局?(创建视图并隐藏它们似乎是一种糟糕的方法)

推荐答案

你需要做这样的事情

先注册多个cell-

[collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCellKind1" bundle:nil] forCellWithReuseIdentifier:@"CollectionViewCellKind1"]
[collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCellKind2" bundle:nil] forCellWithReuseIdentifier:@"CollectionViewCellKind2"]

现在像 show 一样实现 cellForItemAt -

Now implement cellForItemAt like show -

internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if (data.kind == kind1) {
        let cell1 = collectionView.dequeueReusableCell..  as! kind1

        return cell1
    } else {
        let cell2 = collectionView.dequeueReusableCell.. as! kind2

        return cell2
    }
}

通过检查数据类型可以确定单元格.

by checking the type of the data you can determine the cell.

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

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