单击单元格中的按钮获取 UITableViewCell 的 indexPath [英] get indexPath of UITableViewCell on click of Button from Cell

查看:37
本文介绍了单击单元格中的按钮获取 UITableViewCell 的 indexPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UITableViewCell 中有一个按钮(红色十字),点击该按钮我想获得 UITableViewCellindexPath.

I have a button (red color cross) in the UITableViewCell and on click of that button I want to get indexPath of the UITableViewCell.

现在我像这样为每个按钮分配标签cell.closeButton.tag = indexPath.section单击按钮后,我会得到 indexPath.section 值,如下所示:

Right now I am assigning tag to each of the button like this cell.closeButton.tag = indexPath.section and the on click of the button I get the indexPath.section value like this:

@IBAction func closeImageButtonPressed(sender: AnyObject) {
  data.removeAtIndex(sender.tag)
  tableView.reloadData()
}

这是正确的实施方式还是有其他干净的方式来做到这一点?

Is this the right way of implementation or is there any other clean way to do this?

推荐答案

使用委托:

MyCell.swift:

import UIKit

//1. delegate method
protocol MyCellDelegate: AnyObject {
    func btnCloseTapped(cell: MyCell)
}

class MyCell: UICollectionViewCell {
    @IBOutlet var btnClose: UIButton!

    //2. create delegate variable
    weak var delegate: MyCellDelegate?

    //3. assign this action to close button
    @IBAction func btnCloseTapped(sender: AnyObject) {
        //4. call delegate method
        //check delegate is not nil with `?`
        delegate?.btnCloseTapped(cell: self)
    }
}

MyViewController.swift:

//5. Conform to delegate method
class MyViewController: UIViewController, MyCellDelegate, UITableViewDataSource,UITableViewDelegate {

    //6. Implement Delegate Method
    func btnCloseTapped(cell: MyCell) {
        //Get the indexpath of cell where button was tapped
        let indexPath = self.collectionView.indexPathForCell(cell)
        print(indexPath!.row)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
        //7. delegate view controller instance to the cell
        cell.delegate = self

        return cell
    }
}

这篇关于单击单元格中的按钮获取 UITableViewCell 的 indexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆