Search code examples
iosswiftuicollectionviewuicollectionviewlayout

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


I have two custom cell classes HomeCell & CreateCell. Ideally, the first cell should be the CreateCell & the HomeCell's should start at the index of '1' (After the first create cell) but currently, the CreateCell and the first HomeCell are overlapping. Is there a way I can set the HomeCell's to start at the index of '1'?

If there is any more code that needs to be provided, let me know.

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
}

Solution

  • Since you want to access 0th element of List on 1st index, you would need to change the code a little bit in your cellForItemAt indexPath:

    cell.list = lists[indexPath.item - 1]
    

    in this way, you will start the HomeCell views from 1st index

    Also You would need to change the count of total items, as there is additional create cell.

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