首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在swift3中显示UICollectionView中两个不同的单元格

如何在swift3中显示UICollectionView中两个不同的单元格
EN

Stack Overflow用户
提问于 2017-07-17 03:16:18
回答 1查看 949关注 0票数 0

我正在尝试使用UICollectionViewCell来实现下面的图像。

但我有三种不同的情况: A)一种特殊的旅行类型,只有前进的旅行时间是可见的。B)可以看到前进和返回的特定类型的旅程(如下图所示)。C)一种特殊类型的旅行有两次向前旅行和两次返回旅行时间。

因此,我尝试使用集合视图来实现此目的。我这样做是否正确,以及如何使用集合视图来实现此逻辑?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-17 03:28:13

我可能会子类化我的UICollectionViewCell,定义所有必要的布局类型枚举,并将其作为自定义方法中的参数在cellForItemAtIndexPath中传递,这样自定义集合视图单元格就知道如何布局自己。

如下所示:

代码语言:javascript
运行
复制
enum MyLayoutType
{
    case layoutA
    case layoutB
    case layoutC
}

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource
{
    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }

// MARK: Collection View DataSource

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
    {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return 10
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCustomCVCell", for: indexPath) as! MyCustomCVCell

        // Decide here what layout type you would like to set

        cell.setUpWithType(layoutType: .layoutA)
        return cell
    }
}

然后,在您的自定义集合视图单元格子类中(不要忘记在接口构建器文件中分配custom类):

代码语言:javascript
运行
复制
class MyCustomCVCell: UICollectionViewCell
{
    func setUpWithType(layoutType: MyLayoutType)
    {
        switch layoutType
        {
        case .layoutA:
            self.backgroundColor = .red
        case .layoutB:
            self.backgroundColor = .yellow
        case .layoutC:
            self.backgroundColor = .blue
        }
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45132433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档