0

I have a UICollectionView which has a long press gesture attached to it. It works fine when i'm pressing on a cell but if the touched area isn't a cell the app crashes with EXC_BREAKPOINT

It crashes on the

if let indexPath : NSIndexPath = collectView.indexPathForItemAtPoint(point)! { 

line. I believe that i need to check that the point is actually a cell but i'm not sure what to check for

the code is as follows

@IBAction func longPressCell(sender: UILongPressGestureRecognizer) {
    if (sender.state == UIGestureRecognizerState.Began) {
        if let point : CGPoint = sender.locationInView(self.collectionView) {
            if let collectView = self.collectionView {
                if let indexPath : NSIndexPath = collectView.indexPathForItemAtPoint(point)! {
                    let adopt : UserPet = self.fetchedResultsController.objectAtIndexPath(indexPath) as! UserPet
                    NSLog("Adopt: \(adopt)")
                }
            }
        }

    }
}
Ceri Turner
  • 830
  • 2
  • 12
  • 36
  • I think the problem might be if you touch outside of a cell, then the index path returned via indexPathForItemAtPoint() is nil, and you use a force unwrap on the optional using the ! operator, which cannot be used on a missing (nil) value. You should check if the returned value is not nil first then proceed, and - depending on your business logic - discard the gesture if you don't need to handle it outside of a cell. – Zoltán Lippai May 11 '16 at 18:57
  • 1
    EDIT for the above: I think you need to drop the ! operator at the end of the line to make it work fine. Shouldn't you have a compiler warning/error though "Initializer for conditional binding must have Optional type, not 'NSIndexPath'" ? – Zoltán Lippai May 11 '16 at 19:16
  • Thanks, resolved it with a if collectView.indexPathForItemAtPoint(point) != nil { – Ceri Turner May 11 '16 at 20:04

1 Answers1

0

collectView.indexPathForItemAtPoint(point) != nil { Solved it

Ceri Turner
  • 830
  • 2
  • 12
  • 36