如何将 collectionview 单元格设置为从索引“1”而不是“0”开始 - Swift

How to set collectionview cell to start at index '1' not '0' - Swift

我有两个自定义单元格 类 HomeCellCreateCell。理想情况下,第一个单元格应该是 CreateCell 并且 HomeCell's 应该从索引“1”开始(在第一个创建单元格之后),但目前,CreateCell 和第一个 HomeCell 是重叠的。有没有办法可以将 HomeCell's 设置为从索引“1”开始?

如果需要提供更多代码,请告诉我。

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.row == 0 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CreateCell", for: indexPath) as! CreateCell
        //configure your cell here...
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCell", for: indexPath) as! HomeCell
        cell.list = lists[indexPath.item]
        //configure your cell with list
        return cell
    }
}

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

由于您想在第一个索引上访问列表的第 0 个元素,因此您需要稍微更改 cellForItemAt indexPath:

中的代码
cell.list = lists[indexPath.item - 1]

这样,您将从第一个索引

开始HomeCell视图

此外,您还需要更改项目总数,因为还有额外的创建单元格。

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return lists.count+1
}

indexPath.item代替indexPath.row

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

    if indexPath.item == 0 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CreateCell", for: indexPath) as! CreateCell
        //configure your cell here...
        return cell
    } else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCell", for: indexPath) as! HomeCell
        cell.list = lists[indexPath.item]
        //configure your cell with list
        return cell
    }
}