SWIFT:如何获得indexpath.row当在单元格中的一个按钮被窃听? [英] swift: how to get the indexpath.row when a button in a cell is tapped?
问题描述
我有按钮的实现代码如下,我想用indexpath.row当其中一个被窃听。
这是我目前有,但它始终是0
VAR点= INT()
FUNC按钮pressed(发件人:AnyObject){
让pointInTable:CGPoint = sender.convertPoint(sender.bounds.origin,toView:self.tableView)
让cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
的println(cellIndexPath)
点= cellIndexPath!.row
的println(点)
}
giorashc几乎与他的答案了吧,但有code的下一行认为需要。正确的答案是:
让按钮=发件人作为!的UIButton
让视图= button.superview!
让细胞= view.superview的! <此处&GT您的自定义单元格名称; 让indexPath = itemTable.indexPathForCell(细胞)
这是因为视图一个层次结构具有的tableView细胞作为susequently有自己的'内容的看法,这就是为什么你必须得到这个内容视图的上海华获得细胞本身子视图中。
希望这有助于
雅
编辑:
按评论我就迫使迅速展开收,你应该不希望强制拆开包装,就可以解开安全地使用,如果让条款如下:
VAR indexPath:NSIndexPath!如果让按钮=发送者的? {的UIButton
如果让上海华= {button.superview
如果让细胞= superview.superview作为? MyCellClassHere {
indexPath = itemTable.indexPathForCell(细胞)
}
}
}//检查indexPath价值,如果有的话,在这里。
I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped. This is what I currently have, but it always is 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)
}
giorashc almost had it with his answer, but there was one more line of code that was required. The correct answer would be:
let button = sender as! UIButton
let view = button.superview!
let cell = view.superview as! <Your custom cell name here>
let indexPath = itemTable.indexPathForCell(cell)
This is because within the view heirarchy a tableView has cells as subviews which susequently have their own 'content views' this is why you must get the superview of this content view to get the cell itself.
Hope this helps,
Jacob
EDIT:
As per the comment I received with regard to force unwrapping in swift, should you not want to force unwrap, you can unwrap safely using an if let clause as follows:
var indexPath: NSIndexPath!
if let button = sender as? UIButton {
if let superview = button.superview {
if let cell = superview.superview as? MyCellClassHere {
indexPath = itemTable.indexPathForCell(cell)
}
}
}
// Check for indexPath value, if any, here.
这篇关于SWIFT:如何获得indexpath.row当在单元格中的一个按钮被窃听?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!