点击单元格并获取索引

时间:2015-11-09 18:58:33

标签: swift

当我点击一个单元格时,我想要接收特定于该单元格的索引或其他标识符。代码工作并进入tapped功能。但我怎样才能收到索引或类似内容?

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

    if cell.gestureRecognizers?.count == nil {
        let tap = UITapGestureRecognizer(target: self, action: "tapped:")
        tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
        cell.addGestureRecognizer(tap)
    }

    return cell
}

func tapped(sender: UITapGestureRecognizer) {
    print("tap")  
}

3 个答案:

答案 0 :(得分:1)

Swift 4-4.2 -返回所点击的单元格的索引。

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cellIndex = indexPath[1] // try without [1] returns a list.
print(indexPath[1])
chapterIndexDelegate.didTapChapterSelection(chapterIndex: test)
}

答案 1 :(得分:0)

想一想。 sender是点击手势识别器。 g.r.的view是单元格。现在,您可以询问集合视图此单元格的索引路径是什么(indexPathForCell:)。

enter image description here

答案 2 :(得分:0)

Build on Matts回答

首先我们添加点按识别器

let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapped(tapGestureRecognizer:)))
cell.textView.addGestureRecognizer(tap)

然后我们使用以下函数来获取indexPath

@objc func tapped(tapGestureRecognizer: UITapGestureRecognizer){
    //textField or what ever view you decide to have the tap recogniser on
    if let textField = tapGestureRecognizer.view as? UITextField {

        // get the cell from the textfields superview.superview
        // textField.superView would return the content view within the cell
        if let cell = textField.superview?.superview  as? UITableViewCell{

            // tableview we defined either in storyboard or globally at top of the class

            guard let indexPath = self.tableView.indexPath(for: cell) else {return}
            print("index path =\(indexPath)")

// then finally if you wanted to pass the indexPath to the main tableView Delegate

                self.tableView(self.tableView, didSelectRowAt: indexPath)

            }
    }
}