在Swift中从单元格的indexPath获取索引整数

4
这里有两个函数。

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

当发生双击手势事件时,我试图从此函数向我的第二个函数发送indexPath。所以我的操作调用doubleTap:

在我的第二个函数中,我试图使用sender获取单元格的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个回答

19
你可以使用以下代码从触点中检索出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

2
谢谢@Unheilig!这帮助我检索了索引! - dbrownjave

9
假设您没有使用节(section),则可通过以下方式获取项目编号:
indexPath.item

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接