如何访问自定义TableViewCell中的button的索引path?

我创build了一个自定义的TableViewCell并在单元格中放置了一个button。 当按下button时,在tableviewcell.swift文件中, IBAction func被执行。 我不知道如何确定button所在的单元格的索引path。 我正在尝试使用以下内容

  @IBAction func employeeAtLunch(sender: AnyObject) { let indexPath = (self.superview as! UITableView).indexPathForCell(self) println("indexPath?.row") } 

但我得到以下错误点击: Could not cast value of type 'UITableViewWrapperView' to 'UITableView'

任何帮助如何访问单元格的索引path?

你可以在你的单元格中为其行的属性UIButton

 class MyButton: UIButton { var row: Int? } 

然后,当您设置您的表视图,在cellForRowAtIndexPath方法,您设置row属性:

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // ... cell.button.row = indexPath.row // ... } 

这样当行动发生时,你可以得到正确的行:

 @IBAction func employeeAtLunch(sender: MyButton) { if let row = sender.row { // access the row } } 

你只是假设单元的直接超视图是表视图 – 错误的。 为什么应该这样(而事实上并非如此)没有特别的理由。 更less的假设工作! 你需要继续走上超级连锁店,直到你到达桌面,像这样:

 var v : UIView = self do { v = v.superview! } while !(v is UITableView) 

现在v是表视图,你可以继续计算这是什么行。

然而,我实际上做的是让我起床,而不是从牢房到桌子,而是从button到牢房。 技术是完全一样的:

 var v : UIView = sender as! UIView do { v = v.superview! } while !(v is UITableViewCell) 

这样做的button的操作方法,其中sender是button。 如果操作方法的目标是表视图控制器,它有权访问表,问题就解决了。

在你的情况下,我将添加一个标签到你的button来确定它是哪一行。 每当我在callbackcellForRowAtIndexPathconfiguration单元格,我更新这个标签值。

当一个button被点击时,处理程序总是指定button被按下。 通过为该button定义标签,您可以知道按下哪一行的button。

 @IBAction func buttonPressed(sender: AnyObject) { //convert to UIButton if let btn = sender as? UIButton { let rowId = btn.tag //do your works } } 

如果你的tableview有超过1个部分,你将不得不正确设置标签的值。

第二个解决scheme更好:在你的tableView中获取button的位置,然后在你的tableview中获得该位置的indexpath:

 let position = sender.convertPoint(CGPointZero, toView: self.tblMain) let indexPath = self.tblMain.indexPathForRowAtPoint(position)