从特定的索引路径中取出自定义单元格SWIFT

从特定的索引路径中取出自定义单元格SWIFT

问题描述:

我有UICollectionView,我正在下载图像并在单元格中显示它们。我的第一个单元格是屏幕宽度并包含一个按钮,其余的是一般单元格。应用程序只deques前2个单元格,应该有3个单元格。从特定的索引路径中取出自定义单元格SWIFT

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 


} 

我的观点:

enter image description here

有应该是3个图像那里的细胞,其中一人在第一索引dequed。

我出来的想法,解决方案的任何想法?

+0

“当我选择第一个索引上的单元格时,它没有按预期做出响应。”代码在哪里? – Larme

+0

@Larme更新问题和查询。单元格选择现在表现良好。分离细胞是一个问题。再次看到问题。对不起,询问错误。 –

+0

部分中的项目数返回...? – Larme

let userImages = userposts[indexPath.row]

在代码这一点上,是indexPath.row>是基于0 0
阵列,所以所述第一小区(indexPath.row == 1)越来越您的阵列中的第二项(user posts[1] ),这是你想要的第二个图像。

我能想到几个简单的变化:

  • 更改你所访问的指标,如:
    let userImages = userposts[indexPath.row - 1]
  • 加1到你userposts.count价值numberOfItemsInSection:
  • 分裂您collectionView分为多个部分,所以顶部单元格(UploadNewCell)是第0部分,底部的三个ProfileCell是第二部分:这允许您检查indexPath.section,并将direc TLY从行:
    let userImages = userposts[indexPath.row]

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

+0

这是完美的谢谢。我只是给索引加了+1。我的错。这是很好的答案。感谢您的及时回复。欢呼 –

+1

而且,我只是尝试了部分。我也认为,Enum将是一个更好的选择来消除未来的肮脏错误 –