【问题标题】:How can i load multiple custom views in collection view swift如何在集合视图中快速加载多个自定义视图
【发布时间】:2017-07-01 08:43:31
【问题描述】:

我有两个集合视图单元 A 和 B,我需要同时加载这些单元。但是我没有找到任何解决方案

         firstCollectionView.register(UINib(nibName: "A", bundle:  Bundle.main), forCellWithReuseIdentifier: "A")
     firstCollectionView.register(UINib(nibName: "B", bundle:  Bundle.main), forCellWithReuseIdentifier: "B")

这是两个视图,如何一次加载两个视图。

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "A", for:indexPath) as? A

【问题讨论】:

  • 在同一节或同一单元格或任何其他条件?
  • 同时是什么意思? ...您需要两个不同的单元格还是?
  • 你可以同时对A和B进行排序,然后选择你想要返回的一个
  • 我的意思是先加载 A,然后再加载 B。
  • 检查 indexPath 编号并返回正确的单元格,仅此而已

标签: ios swift uicollectionview custom-view


【解决方案1】:

您想如何划分不同的细胞类型?带号码?例如,如果 raw = 0,2,4,6 等,您将拥有 firstCell,如果 raw = 1,3,5 等,您将拥有 secendCell?

所以也许是这样的:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = UICollectionViewCell()

        cell = collectionView.register(UINib(nibName: "B", bundle:  Bundle.main), forCellWithReuseIdentifier: "B")

        if indexPath.row % 2 == 0 {
            cell = collectionView..register(UINib(nibName: "A", bundle:  Bundle.main), forCellWithReuseIdentifier: "A")
        }

        return cell
    }

【讨论】:

    【解决方案2】:

    viewDidLoad:注册CustomCollectionViewCell

        var nib1 = UINib(nibName: "CustomCollectionViewCell1", bundle: nil)
        self.firstCollectionView().registerNib(nib1, forCellReuseIdentifier: "CustomCell1")
        var nib2 = UINib(nibName: "CustomCollectionViewCell2", bundle: nil)
        self.firstCollectionView().registerNib(nib2, forCellReuseIdentifier: "CustomCell2")
    

    现在在这里返回您的单元格cellForItemAtIndexPath: 方法,

    //As per your condition check cell index or section or any other your condition.
    
    
     if indexPath.row % 2 == 0 {  
    
          // Create an instance of CustomCollectionViewCell1
         var cell: CustomCollectionViewCell1? = tableView.dequeueReusableCell(withIdentifier: "CustomCell1")
            if self.cell == nil {
                self.cell = CustomCollectionViewCell1(style: .subtitle, reuseIdentifier: "CustomCell1")
            }
         return cell!
    
        }else{
          // Create an instance of CustomCollectionViewCell2
         var cell: CustomCollectionViewCell2? = tableView.dequeueReusableCell(withIdentifier: "CustomCell2")
            if self.cell == nil {
                self.cell = CustomCollectionViewCell2(style: .subtitle, reuseIdentifier: "CustomCell2")
            }
         return cell!
        }
    

    【讨论】: