I'm working on a "trading" application where I would like to have a static number of cells.
On load, users will see 5 cells, each displaying a label that says "Add."
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.
答案 0 :(得分:4)
您需要在viewController中继承 UICollectionViewDelegate 和 UICollectionViewDataSource 协议,然后您需要实现 numberOfItemsInSection 和 cellForItemAtIndexPath < / em>功能。 除此之外,您需要在故事板中创建两种类型的单元格并将它们子类化,在以下代码中,我将假设您调用 AddedPlayerCell 和 DefaultCell 您的单元格,我将假设每个单元格都有一个名为 labelText 的标签。
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;
}
}
答案 1 :(得分:0)
为了管理两种不同的细胞类型,您可以:
"Add"
和另一个"Info"
。 "Add"
单元格原型将包含标签"Add"
,"Info"
单元格原型将包含显示播放器信息的字段。var showingAdd = [true, true, true, true, true]
在cellForItemAtIndexPath
中,检查showingAdd
数组以确定出列单元格时要使用的标识符:
let identifier = showingAdd[indexPath.row] ? "Add" : "Info"
let cell = dequeueReusableCellWithIdentifer(identifier...)
if !showingAdd[indexPath.row] {
// configure the cell with the proper player info
// retrieve info from info property array item created in
// step 4.
let player = playerInfo[indexPath.row]
cell.playerName = player.name
...
}
在didSelectItemAtIndexPath
中选择单元格后,检查它是否显示添加,然后相应地处理它:
if showingAdd[indexPath.row] {
// query user to get player info
// store the info in a property array indexed by `indexPath.row`
playerInfo[indexPath.row] = PlayerInfo(name: name, ...)
showingAdd[indexPath.row] = false
// trigger a reload for this item
collectionView.reloadItemsAtIndexPaths([indexPath])
}