来自特定索引路径的双端自定义单元格 SWIFT

Deque custom cells from specific indexpath SWIFT

我有 UICollectionView,我正在下载图像并将它们显示在单元格中。我的第一个单元格是屏幕宽度并包含一个按钮,其余是一般单元格。该应用程序仅对前 2 个单元格进行双端队列处理,应该有 3 个单元格。

我的cellForItemAtIndexPath函数:

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

    if indexPath.row == 0 {
        print("yay")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UploadNewCell", for: indexPath) as! UploadNewCell
        return cell
    }else if indexPath.row > 0 {
        let userImages = userposts[indexPath.row]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfileCell", for: indexPath) as! ProfileCell
            cell.fillCells(uid: uid!, userPost: userImages)
            return cell
    }else{
        return ProfileCell()
    }
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if indexPath.row == 0 {
        print("hellowold")
    } else {
        let selecteditem : String!
        selecteditem = userposts[indexPath.row]
        performSegue(withIdentifier: "lol", sender: selecteditem)
    }
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return userposts.count


}

我的看法:

下面的单元格中应该有 3 张图片,其中一张在第一个索引中出列。

我没有想法,对解决方案有什么想法吗?

let userImages = userposts[indexPath.row]

此时在您的代码中,indexPath.row > 0。
数组是从 0 开始的,所以第一个单元格 (indexPath.row == 1) 获取数组中的第二个项目 (user posts[1]),这是你想要的第二个图像。

我可以想到几个简单的更改:

  • 更改您正在访问的索引,例如:
    let userImages = userposts[indexPath.row - 1]
  • numberOfItemsInSection:
  • 中为您的 userposts.count 值加 1
  • 将您的 collectionView 分成多个部分,因此顶部单元格 (UploadNewCell) 是第 0 部分,底部三个 ProfileCell 是第二部分:这允许您检查 indexPath.section,直接从行赋值:
    let userImages = userposts[indexPath.row]

注意:我实际上建议进一步修改第二个选项的代码,以便为 SectionType 创建一个枚举。这使您可以对潜在值执行 switch,从而避免讨厌的默认实现,并提高代码的可读性。