![](/img/trans.png)
[英]UICollectionView DidDeselectItemAtIndexPath method not called in Swift
[英]iPhone application crashes in didDeselectItemAtIndexPath of UICollectionView
我已经在我的应用程序中实现了UICollectionView
,当我从UICollectionView
取消选择图像时,我正在从NSMutableArray
删除该UIImage
。 现在我的问题是,如果图像多于两个,并且我取消选择该图像,那么我的应用程序将崩溃。
并得到错误是
由于未捕获的异常“ NSRangeException”而终止应用程序,原因:“ ***-[__ NSArrayM removeObjectAtIndex:]:索引2超出范围[0 .. 1]”
这是我的下面的代码
- (void)collectionView:(UICollectionView *)collectionView
didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
[selectedImagesArray removeObjectAtIndex:indexPath.row];
}
我正在获取超出该数组的indexPath
。
IndexPath
不一定具有row属性,因此可能为nil。 如果为零,您将看到崩溃
检查数组计数是否大于indexPath.row属性,然后删除或检查该索引的数组元素是否存在,如果是,则删除该元素
if(selectedImageArray[indexPath.row] != nil) {
[selectedImagesArray removeObjectAtIndex:indexPath.row];
}
Indexpath.row
将返回您未选择的数组索引的实际数组的索引。 因此,您必须在SelectedArray
找到相同的元素,然后才能从选定数组中删除该图像。
例如
实际数组对象
[1,2,3,4,5,6,7,8,9,10]
从中选择对象
[1,5,7]
因此对象[1,5,7]
将处于选定状态,并且也处于SelectedArray
。
当您在那时选择对象7
时, Indexpath.row
将返回您6
并且您直接从SelectedArray
删除索引6
,该索引不可用,因此您遇到此错误。
您必须使用indexPath.item。 通常在collectionView中使用。 IndexPath.row用于TableView。
无论如何,请在其周围放置一个if条件,以检查该索引是否存在。
添加以下代码行以处理检查:
if ([indexPath.row] < [selectedImagesArray count]) {
[selectedImagesArray removeObjectAtIndex:indexPath.row];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.