Ben Wong
Ben Wong

Reputation: 701

Swift, CollectionView, fatal error: Index out of range

I downloaded a collection of images and loaded them into a collectionView. I want to be able to add the individual item selected to an array I declared globally whenever I press on an individual cell so then I can loop through them to be deleted from core data later. This line prints fine in terms of the order of the item - print("You selected cell #(indexPath.item)!"), but the 2nd time I press another cell to add to the array, I get an fatal error: Index out of range error. I don't know what I'm getting this.

var selectedCell: [Int] =  []     -> Declared globally


    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // handle tap events

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell


        print("You selected cell #\(indexPath.item)!")

        if self.selectedCell.contains(indexPath.item){
            print("Item already added")
        } else {
            self.selectedCell.append(indexPath.item)
        }

        if selectedCell.count > 0 {
            toolbarButton.title = "Remove Item"
        }

//        let selectCell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
//        selectCell.contentView.backgroundColor = UIColor.whiteColor()

    }

Upvotes: 1

Views: 3087

Answers (1)

serge-k
serge-k

Reputation: 3502

iOS 9.3, Xcode 7.3

I honestly think that "fatal error: Index out of range" does not apply to the simpler array of integer indexes that you declared, I think that it is associated to the index of the collection view itself.

Looks like you are conforming to the various protocols of UICollectionView, namely UICollectionViewDataSource, UICollectionViewDelegate, because you are at least receiving callbacks to the cell selected method.

First thing that jumps at me is...

Where is title property for toolbarButton declared, is it a custom subclass of UIButton, because title is not a set able property of standard UIButton class. This is how you'd typically set the title of a UIBUtton...

self.toolbarButton.setTitle("Remove Item", forState: .Normal)

Another thing is,

 let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MyCollectionViewCell

The variable cell is never used in that function, it should give you a warning.

Also, check all of your uses of the array variable selectedCell, in the if statement where you check the count value you are not using self.selectedCell for example. Not sure what this would do, but I think this would cause your array to get re-synthesized, so count will be reset each time.

There are few other items that I don't understand, here is the code that I would use. Please check your code and syntax.

The following code works:

var selectedCell: [Int] =  []

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
    // handle tap events

    print("You selected cell #\(indexPath.item)!")

    if (self.selectedCell.contains(indexPath.item))
    {
        print("Item already added")
    }
    else
    {
        self.selectedCell.append(indexPath.item)
    }

    print("selectedCell.count: \(self.selectedCell.count)")

    if (self.selectedCell.count > 0)
    {
        self.toolbarButton.setTitle("Remove Item", forState: .Normal)

        print("selectedCell: \(self.selectedCell)")
    }
    else
    {
        //nil
    }
}

The output would look something like this:

enter image description here

Note: When you click the same cell twice it is not added (in this case 8), once you have at least 1 item in the array, then the button title changes.

If you still can not figure it out, then see this post, it explains how to implement a collection view very well: https://stackoverflow.com/a/31735229/4018041

Hope this helps! Cheers.

Upvotes: 1

Related Questions