如何在UICollectionView中访问所选单元格的索引

时间:2016-02-11 13:51:47

标签: ios swift uicollectionview

我的UICollectionView中有一些单元格,我在其中创建按钮:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
    let button = UIButton(frame: CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height))
    button.setTitle("ButtonTitle")
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    return cell
}

然后我向按钮添加一个动作,切换到一个新的ViewController,将按钮的名称设置为标题:

func buttonAction(sender: AnyObject?) {
    let vc = NewViewController()
    vc.title = sender!.titleLabel!!.text
    revealViewController().pushFrontViewController(vc, animated: true)
}

但我现在也想访问所选单元格/按钮的索引。有人知道怎么做吗?

4 个答案:

答案 0 :(得分:3)

喜欢

<强>步骤1

 button.tag = indexPath.row
 button.setTitle("ButtonTitle")
 button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

<强>步骤-2

func buttonAction(sender: UIButton) {

    if let sendertitle = sender.titleLabel?.text {

        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("NewViewControllerIdentifier") as? NewViewController
        vc.title = sendertitle

        revealViewController().pushFrontViewController(vc, animated: true)
    }
}

选择 - 2

如果你想实现简单的方式

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)

    return cell
}

on didSelect call

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    let vc = self.storyboard?.instantiateViewControllerWithIdentifier("NewViewControllerIdentifier") as? NewViewController
    vc.indexPath = indexPath.row

    revealViewController().pushFrontViewController(vc, animated: true)
 }

答案 1 :(得分:2)

在你的buttonAction中:

    let btn = sender as! UIButton
    let point = btn.convertPoint(btn.bounds.origin, toView: self.tableView)
    let indexPath = self.tableView.indexPathForRowAtPoint(point)

答案 2 :(得分:1)

只需使用此方法:

let point = button.convertPoint(btn.bounds.origin, toView: self.collectionView)
let mypath = self.collectionView?.indexPathForItemAtPoint(point)

使用按钮位置获取正确的索引路径

答案 3 :(得分:0)

如果整个单元格显示一个按钮,您可以删除按钮并执行以下操作:

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    // Perform any action you want after a cell is tapped
    // Access the selected cell's index with the indexPath.row value

}