swift - 错误: Array index out of range Swift

标签 swift core-data uicollectionview

var longPressTarget: (cell: UICollectionViewCell, indexPath: NSIndexPath)?

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath){
   longPressTarget = (cell: self.collectionView(collectionView, cellForItemAtIndexPath: indexPath), indexPath: indexPath)
}

func longPressHandler(recognizer: UILongPressGestureRecognizer) {
        if recognizer.state == UIGestureRecognizerState.Began {
            if let _longPressTarget = longPressTarget {   
                let entity = coin[_longPressTarget.indexPath.item]
                let contextMenuController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
                let deleteAction = UIAlertAction(title: entity.pendingDelete ? "Undelete" : "Delete", style: UIAlertActionStyle.Default, handler: togglePendingDelete)
            }
        }
}

错误位于:letentity = coin[_longPressTarget.indexPath.item]

硬币:

var coin: [Receipts] = [Receipts] ()    

-coin 在 viewDidLoad

之前调用

收据:核心数据中的实体

我不明白为什么硬币数组超出范围?

我正在尝试使用长按手势识别器从核心数据中删除 UICollectionViewCell

最佳答案

让我们部分修复您的代码,首先您不会在调用方法 cellForItemAtIndexPath: 的某个 indexPath 处访问单元格。您可以像这样使用 cellForItemAtIndexPath(_:) 方法:

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
     longPressTarget = (cell: self.collectionView?.cellForItemAtIndexPath(indexPath), indexPath: indexPath)
} 

尽管如此,在你的情况下,我不知道你需要什么细胞,但是......

在您的其他方法中,您需要使用 indexPath.row 而不是 indexPath.item,两者有所不同。所以你的代码应该是这样的:

func longPressHandler(recognizer: UILongPressGestureRecognizer) {
    if recognizer.state == UIGestureRecognizerState.Began {
        if let _longPressTarget = longPressTarget {
            let indexPath = _longPressTarget.indexPath
            let entity = coin[indexPath.row]
            let contextMenuController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
            let deleteAction = UIAlertAction(title: entity.pendingDelete ? "Undelete" : "Delete", style: UIAlertActionStyle.Default, handler: togglePendingDelete)
        }
    }
}

希望这对您有帮助。

关于swift - 错误: Array index out of range Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36020815/

相关文章:

swift - NSOpenPanel继承和 "designated initializer"

ios - NSFetchedResultsController 需要非零获取请求和 ManagedObjectContext 错误

cocoa - 观察 NSManagedObject 属性的变化 : how to avoid looping?

c# - Xamarin.Forms Collection View

ios - Swift - 无法使 : UICollectionElementKindCell with identifier 类型的 View 出队

表格 View 单元格图像中的 ios 故障

swift - 如何将模块导入到xcode中

iOS - 修复 cellForItemAtIndexPath 图像加载问题

ios - Web View 中的编程后退按钮 (WebKit)

ios - Swift:保存(覆盖)和加载 CoreData