Swift,CollectionView,致命错误:索引超出范围

时间:2021-04-24 16:40:01

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.

我下载了一组图像并将它们加载到collectionView中。我希望能够将所选的单个项目添加到我在全局声明的数组中,只要我按下单个单元格,然后我就可以循环它们以便稍后从核心数据中删除。这条线在项目的顺序打印很好 - 打印(“你选择的单元格#(indexPath.item)!”),但是第二次按下另一个单元格添加到数组时,我得到一个致命的错误:索引超出范围错误。我不知道我得到了什么。

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()

    }

1 个解决方案

#1


1  

iOS 9.3, Xcode 7.3

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.

看起来你符合UICollectionView的各种协议,即UICollectionViewDataSource,UICollectionViewDelegate,因为你至少接收到单元格选择方法的回调。

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...

toolbarButton声明的title属性在哪里,它是UIButton的自定义子类,因为title不是标准UIButton类的setable属性。这就是你通常设置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.

另外,检查所有对数组变量selectedCell的使用,在if语句中检查你没有使用self.selectedCell的计数值。不知道这会做什么,但我认为这会导致你的数组重新合成,所以每次都会重置计数。

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:

输出看起来像这样:

Swift,CollectionView,致命错误:索引超出范围

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.

注意:当您单击两次相同的单元格时,它不会被添加(在本例中为8),一旦数组中至少有一个项目,则按钮标题会更改。

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

如果你仍然无法弄明白,那么请看这篇文章,它解释了如何很好地实现集合视图:https://*.com/a/31735229/4018041

Hope this helps! Cheers.

希望这可以帮助!干杯。

#1


1  

iOS 9.3, Xcode 7.3

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.

看起来你符合UICollectionView的各种协议,即UICollectionViewDataSource,UICollectionViewDelegate,因为你至少接收到单元格选择方法的回调。

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...

toolbarButton声明的title属性在哪里,它是UIButton的自定义子类,因为title不是标准UIButton类的setable属性。这就是你通常设置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.

另外,检查所有对数组变量selectedCell的使用,在if语句中检查你没有使用self.selectedCell的计数值。不知道这会做什么,但我认为这会导致你的数组重新合成,所以每次都会重置计数。

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:

输出看起来像这样:

Swift,CollectionView,致命错误:索引超出范围

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.

注意:当您单击两次相同的单元格时,它不会被添加(在本例中为8),一旦数组中至少有一个项目,则按钮标题会更改。

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

如果你仍然无法弄明白,那么请看这篇文章,它解释了如何很好地实现集合视图:https://*.com/a/31735229/4018041

Hope this helps! Cheers.

希望这可以帮助!干杯。