在集合视图中显示两个不同的单元格 - Swift 2.0 iOS [英] Displaying two different cells in a collection view - Swift 2.0 iOS

查看:220
本文介绍了在集合视图中显示两个不同的单元格 - Swift 2.0 iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个交易应用程序,我希望有一个静态的单元格数。

I'm working on a "trading" application where I would like to have a static number of cells.

在加载时,用户将看到5个单元格,每个单元格显示标有添加的标签。

On load, users will see 5 cells, each displaying a label that says "Add."

当添加播放器时,该单元格显示播放器信息,其他4个单元格仍显示添加标签。另外一个是添加,2个单元格有玩家信息,3个单元格有添加

When a "player" is added, that cell displays the players information, the other 4 cells still display the "Add" label. Another is added, 2 cells have player information, 3 have the "Add"

我对此有一段时间。谁能指出我的正确方向?我有自定义标签设置,我认为我的逻辑可能只是关于如何正确执行此操作。

I'm having a hell of a time with this. Can anyone point my in the right direction? I have custom labels setup, I think my logic may just be off on how to perform this correctly.

推荐答案

您需要子类viewController中的 UICollectionViewDelegate UICollectionViewDataSource 协议,则需要实现 numberOfItemsInSection cellForItemAtIndexPath 函数。
除此之外,你需要在故事板中创建两种类型的单元格并将它们子类化,在下面的代码中我将假设你调用 AddedPlayerCell DefaultCell 你的我会假设每个单元格都有一个名为 labelText 的标签。

You need to subclass the UICollectionViewDelegate and UICollectionViewDataSource protocols in your viewController, then you need to implement the numberOfItemsInSection and cellForItemAtIndexPath functions. Additionally to that you need to create two type of cells in your storyboard and subclass them, in the following code i will suppose that you call AddedPlayerCell and DefaultCell your cells, i will suppose that each cell has a label called labelText too.

let players = ["Player1","Player2"] //players added till now
let numberOfCells = 5

//Here you set the number of cell in your collectionView    
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return max(players.count,numberOfCells);
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
            if((indexPath.row + 1) < self.players.count){ //If index of cell is less than the number of players then display the player

                    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yourIdentifierForAddedPlayerCell", forIndexPath: indexPath) as! AddedPlayerCell
                    cell.labelText.text = self.players[indexPath.row] //Display player
                    return cell;

            }else{//Else display DefaultCell
                    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yourIdentifierForDefaultCell", forIndexPath: indexPath) as! DefaultCell
                    cell.labelText.text = "Add"
                    return cell;
            }
}

这篇关于在集合视图中显示两个不同的单元格 - Swift 2.0 iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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