如何在Swift中以编程方式设置动态数量的集合视图

问题描述 投票:0回答:2

我有很多Decks的列表,其中主要有一个name和一个Cards的列表。

我需要能够为每个卡片组创建一个单独的UICollectionView,其中每个单元格应该代表一个带有单张卡片名称的按钮,并且我需要能够识别出哪个单元格的按钮被点击了。这意味着我需要同时允许UICollectionViewCell(卡片组列表)和UICollectionViewCell(卡列表)的动态数量。下图大致显示了我想做的事情。

enter image description here

我大致了解如何识别点击了哪个单元格的按钮。但是,我不确定如何实现numberOfItemsInSectioncellForItemAt(例如要使用的重用标识符)功能,因为在编译过程中我不知道每个卡座中有多少个卡座和多少张卡时间。

实现Decks时是否有一种方法可以索引UICollectionView列表,以便我可以正确地实现所需的方法?还是我应该做一个更简单/更有效的方法?谢谢大家!

swift dynamic uicollectionview uicollectionviewcell
2个回答
0
投票

您已经有了一个解决方案,您有了一个列表,其中有一个项目,因此您必须动态实现,因此您只需要在列表中计算多个项目。

为此,您可以使用items.count来执行功能:-

func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection部分:Int)-> Int{

    return items.count

}

func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath)-> UICollectionViewCell{

让单元格= collectionView.dequeueReusableCell(withReuseIdentifier:“您的单元格标识符名称”,用于:indexPath)

//这将从项目列表中返回每个项目名称并显示在单元格中

cell.textLabel.text = item [indexPath.row]

返回单元格

}

func collectionView(_ collectionView:UICollectionView,didSelectItemAt indexPath:IndexPath){

//在这里,当用户选择特定单元格时,您将编写代码

}


0
投票

这是您的简单解决方案。

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //number of items in Decks Array will be its count
    return Decks.count  //It will tell the collection view how much cell will be there
}

//Setup your resuable cell here

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Your Cell Identifier Name", for: indexPath)
  // This will return a each item name from the item list and display in to a cell

  cell.textLabel.text = Decks[indexPath.row].name
  return cell

}

 //Now get to know which cell is tapped
 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

  print(Decks[indexPath.row].name)
  // Here you write a code when user select a particular cell

 }
© www.soinside.com 2019 - 2024. All rights reserved.