从索引路径获取索引整数从Swift中的单元格获取

时间:2015-08-20 00:14:17

标签: ios swift swift2

这是两个功能。

第一个功能是我为UICollectionView中的每个单元格提供手势。

我试图在发生双击手势事件时将indexPath从此函数发送到我的第二个函数。所以我的动作调用doubleTap:

在我的第二个函数中,我试图使用发送者来获取单元格的indexPath。我能够得到indexPath,当我记录时,打印出 “0xc000000000078016> {length = 2,path = 0 - 0}” 点击第一个单元格。

当我点击第一个单元格时,如何得到整数0?

欢迎所有建议。谢谢大家。

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

2 个答案:

答案 0 :(得分:11)

您可以使用以下内容从触摸点检索index,如代码所示:

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

let rowNumber : Int = indexPath.row

//use rowNumber as index for your array.

或者:

let index : Int = (indexPath.section * maxCol) + indexPath.row

答案 1 :(得分:3)

假设您没有使用部分,则会使用

获取项目编号
indexPath.item