我有一个简单的表视图,其中有自定义单元格构建,自定义单元格有两个按钮(稍后它们将用作向下投票和UpVote按钮),有没有办法传递indexPath.row值到按钮,以便我识别单击了哪个单元格按钮?
TablewViewController.swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as CustomTableViewCell
cell.piadaTitulo.text = "Lorem Ipsum"
cell.piadaDescription.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean commodo volutpat lectus, vitae semper tortor finibus at. Cras erat ligula, egestas sed tincidunt eget, condimentum maximus lectus. Aenean varius semper tellus, id congue lacus pretium a"
return cell
}
CustomTableViewCell.Swift
@IBOutlet weak var piadaTitulo: UILabel!
@IBOutlet weak var piadaDescription: UILabel!
@IBAction func piadaUpVote(sender: AnyObject) {
println("UPVOTE clicked")
}
@IBAction func piadaDownVote(sender: AnyObject) {
println("DOWNVOTE clicked")
}
答案 0 :(得分:3)
螺丝标签。使用此扩展名可以轻松找到按钮单元格的indexPath。
// MARK: - UITableView
extension UITableView {
func indexPathForView (view : UIView) -> NSIndexPath? {
let location = view.convertPoint(CGPointZero, toView:self)
return indexPathForRowAtPoint(location)
}
}
@IBAction func pressedButton(sender: AnyObject) {
// For a button press
let button = sender as! UIButton
var indexPath = self.tableView.indexPathForView(button)!
// Do thangs
}
答案 1 :(得分:0)
你也可以得到按钮的超视图,它是单元格本身,你不需要索引路径
sender.superview
此致