Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Index Integer From indexPath From Cell in Swift

Tags:

ios

swift

swift2

Here are two functions.

The first function is where I am giving gestures to each cell in my UICollectionView.

I am trying to send over the indexPath from this function to my second function when ever a double tap gesture event occurs. So my action calls doubleTap:.

In my second function im trying to use the sender to get the indexPath of the cell. I am able to get an indexPath that, when logged, prints out "0xc000000000078016> {length = 2, path = 0 - 0}" when I double tap the first cell.

How do I get just the integer 0, when I tap the first cell?

All suggestions are welcomed. Thank you, everyone.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as myViewCell

    //adding single and double tap gestures for each cell
    /////////////////////////////
    //ISSUE IS SENDING indexPath TO doubleTap FUNC
    var gestureDoubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTap:")
    gestureDoubleTap.numberOfTapsRequired = 2
    cell.addGestureRecognizer(gestureDoubleTap)

    var gestureSingleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTap")
    gestureSingleTap.numberOfTapsRequired = 1
    cell.addGestureRecognizer(gestureSingleTap)

    cell.imgView.image=UIImage(named: imageArray[indexPath.row])

    return cell
}

func doubleTap(sender: UITapGestureRecognizer) {
    var tapLocation = sender.locationInView(self.collectionView)
    var indexPath:NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!

    //var cell = self.collectionView.cellForItemAtIndexPath(indexPath)

    NSLog("double tap")
    NSLog("%@", indexPath)

    //NSLog("%@", cell!)
    //name = imageArray[indexPath]
    //self.performSegueWithIdentifier("segue", sender: nil)
}
like image 490
Cherryholme Avatar asked Nov 28 '22 06:11

Cherryholme


2 Answers

You could use the following to retrieve the index from the touch point as shown in your code:

var indexPath : NSIndexPath = self.collectionView.indexPathForItemAtPoint(tapLocation)!

let rowNumber : Int = indexPath.row

//use rowNumber as index for your array.

Or:

let index : Int = (indexPath.section * maxCol) + indexPath.row
like image 177
Unheilig Avatar answered Nov 30 '22 21:11

Unheilig


Presuming you are not using sections you get the item number with

indexPath.item
like image 25
Mundi Avatar answered Nov 30 '22 20:11

Mundi