SWIFT:当单元格中的按钮被点击时,如何获得indexpath.row?

我有一个带有按钮的表视图,当其中一个按钮被点击时,我想使用indexpath.row。这是我目前所拥有的,但始终是0。

var point = Int()func buttonPressed(sender: AnyObject) {
    let pointInTable: CGPoint =         sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    println(cellIndexPath)
    point = cellIndexPath!.row
    println(point)}

SWIFT:当单元格中的按钮被点击时,如何获得indexpath.row?

温温酱
浏览 1392回答 3
3回答

MMTTMM

吉奥拉什几乎有了答案,但他忽略了一个事实,那就是细胞有多余的contentView图层。因此,我们必须走得更深一点:guard&nbsp;let&nbsp;cell&nbsp;=&nbsp;sender.superview?.superview&nbsp;as?&nbsp;YourCellClassHere&nbsp;else&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;//&nbsp;or&nbsp;fatalError()&nbsp;or&nbsp;whatever}let&nbsp;indexPath&nbsp;=&nbsp;itemTable.indexPath(for:&nbsp;cell)这是因为在视图层次结构中,tableView有单元格作为子视图,这些单元格随后具有自己的“内容视图”-这就是为什么您必须获得此内容视图的SuperView才能获得单元格本身。因此,如果您的按钮包含在子视图中,而不是直接放在单元格的内容视图中,那么您将不得不进行更深层次的访问。上述方法就是这样一种方法,但不一定是最好的方法。虽然它是可以使用的,但它假定了关于UITableViewCell这一点苹果从来没有必要记录下来,比如它的视图层次结构。将来可能会改变这种情况,因此,上述代码的行为很可能是不可预测的。因此,出于寿命和可靠性的原因,我建议采用另一种方法。这篇帖子列出了许多备选方案,我鼓励大家读一读,但我个人最喜欢的内容如下:在单元格类上持有一个闭包的属性,让按钮的操作方法调用它。class&nbsp;MyCell:&nbsp;UITableViewCell&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;button:&nbsp;UIButton! &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;buttonAction:&nbsp;((Any)&nbsp;->&nbsp;Void)? &nbsp;&nbsp;&nbsp;&nbsp;@objc&nbsp;func&nbsp;buttonPressed(sender:&nbsp;Any)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.buttonAction?(sender) &nbsp;&nbsp;&nbsp;&nbsp;}}然后,当您在cellForRowAtIndexPath,您可以为您的闭包分配一个值。func&nbsp;tableView(_&nbsp;tableView:&nbsp;UITableView,&nbsp;cellForRowAt&nbsp;indexPath:&nbsp;IndexPath)&nbsp;->&nbsp;UITableViewCell&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;let&nbsp;cell&nbsp;=&nbsp;tableView.dequeueReusableCellWithIdentifier("Cell")&nbsp;as!&nbsp;MyCell &nbsp;&nbsp;&nbsp;&nbsp;cell.buttonAction&nbsp;=&nbsp;{&nbsp;sender&nbsp;in &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Do&nbsp;whatever&nbsp;you&nbsp;want&nbsp;from&nbsp;your&nbsp;button&nbsp;here.&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;OR&nbsp;&nbsp;&nbsp;&nbsp;cell.buttonAction&nbsp;=&nbsp;buttonPressed(closure:&nbsp;buttonAction,&nbsp;indexPath:&nbsp;indexPath)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;<-&nbsp;Method&nbsp;on&nbsp;the&nbsp;view&nbsp;controller&nbsp;to&nbsp;handle&nbsp;button&nbsp;presses.}通过将处理程序代码移到这里,您可以利用已经存在的indexPath争论。这是一种更安全的方法,因为上面列出的方法不依赖于无文档的特性。
打开App,查看更多内容
随时随地看视频慕课网APP