【问题标题】:reuse UITableViewCell with diferent data用不同的数据重用 UITableViewCell
【发布时间】:2019-11-21 23:57:57
【问题描述】:

我有 2 个不同数据的数组

var array : [String] = ["getMeals", "getMeasure", "getWorkouts"]
var array2 : [String] = ["getStep", "getStep", "getStep"]

我正在尝试从数组中检索图像,但在不同的集合单元格中。

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

    if indexPath.section == 0{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WorkoutCollectionCell", for: indexPath) as! WorkoutCollectionCell
        cell.collectionImage.image = UIImage(named: array[indexPath.row])
        return cell
    }else{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WorkoutCollectionCell", for: indexPath) as! WorkoutCollectionCell
                   cell.collectionImage.image = UIImage(named: array2[indexPath.row])
                   return cell
    }

}

我需要创建另一个 UICollectionViewCell 还是可以使用当前单元格?

【问题讨论】:

  • 简短的回答是肯定的,首先将单元格出列,根据您想要的任何条件分配内容,然后返回单元格。

标签: ios swift uitableview uicollectionview uicollectionviewcell


【解决方案1】:

您可以使用相同的单元格,使用以下代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WorkoutCollectionCell", for: indexPath) as! WorkoutCollectionCell
    if indexPath.section == 0{

        cell.collectionImage.image = UIImage(named: array[indexPath.row])

    }else{

        cell.collectionImage.image = UIImage(named: array2[indexPath.row])

    }
 return cell
}

【讨论】:

    【解决方案2】:

    你需要 1 个类似的数组

    let array  = [["getMeals", "getMeasure", "getWorkouts"],["getStep", "getStep", "getStep"]]
    
    func numberOfSections(in collectionView: UICollectionView) -> Int { 
        return array.count
    } 
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
        return array[section].count 
    } 
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WorkoutCollectionCell", for: indexPath) as! WorkoutCollectionCell
        cell.collectionImage.image = UIImage(named: array[indexPath.section][indexPath.row])
        return cell  
    }
    

    【讨论】:

    • 但现在我有 2 个 collectionViewCells 和 6 个图像
    • 2 在哪里?你只能用 id WorkoutCollectionCell出列 1
    • 您不能将集合单元用于表格,反之亦然
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多