长按UICollectionView中的单元格时,我想显示一个删除按钮。当我单击该单元格时,它将显示,当单击该单元格之外时,它会显示异常"fatal error: unexpectedly found nil while unwrapping an Optional value"如何解决?我的代码如下

func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {


    if gestureReconizer.state == UIGestureRecognizerState.Began
    {
        let p = gestureReconizer.locationInView( self.sectionImageCell._collectionView!)

        let touchedIndexPath : NSIndexPath? =  self.sectionImageCell._collectionView!.indexPathForItemAtPoint(p)!//Here getting exception  when click on outside the cell in a uicollectionview

        if touchedIndexPath != nil {


        for item in sectionImageCell._collectionView!.visibleCells() as! [CollectionViewcell] {

            let indexpath : NSIndexPath = self.sectionImageCell._collectionView!.indexPathForCell(item as CollectionViewcell)!
            let cell : CollectionViewcell = self.sectionImageCell._collectionView!.cellForItemAtIndexPath(indexpath) as! CollectionViewcell


            //Close Button


                if touchedIndexPath == indexpath {
                    if cell._closeBtn.hidden == false {
                        cell._closeBtn.hidden = true
                    }
                    else {
                        cell._closeBtn.hidden = false
                    }
                }
            }
        }

    }

}

最佳答案

self.sectionImageCell._collectionView!.indexPathForItemAtPoint(p)!解开if let,您的问题将得到解决。

10-04 17:00