UICollectionView手势事件

时间:2016-01-20 09:54:53

标签: ios swift uicollectionview uigesturerecognizer

我想在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
                    }
                }
            }
        }

    }

}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

试试这个:

func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {


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

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

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


                }
            }

        }