swift - Swift UICollectionView,最后一个单元格添加另一个单元格
问题描述
所以我有一个UICollectionView
基于numOfPlayers
数组的。我已将其设置为最大玩家数为 7。如果可能,我希望在最后一个单元格UICollectionView
中将另一个单元格(或玩家)添加到数组中。然后,如果它是 7 玩家,它就会变成另一个玩家。
我想减少所需的按钮数量。任何帮助或正确方向的观点。
我想要的数组中的最大值是 7。有检查和平衡以确保它不会超过 7。还有检查以防万一我超过 8。
该数组以 3 个元素中的最小值开始。所以集合视图中显示了 3 个元素,然后第 4 个元素是添加第 4 个元素的单元格。一旦将第 4 个单元格添加到数组中,则第 5 个单元格将成为添加单元格。重复。当数组中有 6 个元素时,第 7 个单元格应该添加一个元素。添加第 7 个元素后,它应该只显示 7 个单元格,并且只有 7 个。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return apl.numOfPlayers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "playerCell", for: indexPath) as! APLCollectionViewCell
cell.backgroundColor = .green
cell.playerLvlLbl.text = "\(apl.numOfPlayers[indexPath.row])"
return cell
}
背景颜色只是查看单元格的占位符。确保他们生成正确的方式。
解决方案
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(apl.numOfPlayers.count < 7) {
return apl.numOfPlayers.count + 1 //add one here for your cell that will be used to add a player
}
return apl.numOfPlayers.count // you could add more checks here to make sure it doesn't go over 7 but in your post you said you already have checks to make sure numOfPlayers is never more then 7 so probably just send this if the inital if fails
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(apl.numOfPlayers.count < 7 && indexPath.row == (apl.numOfPlayers.count + 1)) { // first check if the add cell is present and check if the cell this is laying out is the last cell in the list
//write code here to create a "add cell" something like below
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addCell", for: indexPath) as! AddPlayerCollectionViewCell
cell.backgroundColor = .red
cell.textLabel.text = "Add a new player"
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "playerCell", for: indexPath) as! APLCollectionViewCell
cell.backgroundColor = .green
cell.playerLvlLbl.text = "\(apl.numOfPlayers[indexPath.row])"
return cell
}
}
那么您还应该覆盖 didSelectItemAtIndexPath 方法并确保根据所选单元格是玩家还是要添加新玩家的单元格来更改逻辑
推荐阅读
- ruby - 在数字中插入连字符
- python - Django - URL 和命名空间
- ios - (UILabel) nil, 不能在标签中插入文本
- python - 在 Pandas 中转置或旋转多个列
- php - 购物车项目价格计算,基于 Woocommerce 中选择的“天”自定义字段
- amazon-web-services - AWS API 网关授权方:Cognito + IP 白名单
- r - 尝试语句问题 R
- java - 布尔返回类型的方法在 main() 中不起作用
- c++ - 我需要知道如何扩展程序,以便它读取并转换所有输入数字,直到标准输入文件结束
- kubernetes - Istio 是否提供类似于 Kubernetes 的仪表板(目前)?