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/