我更喜欢使用委托
class protocol ButtonCellDelegate: class {
func didPressButtonInCellAt(_ indexPath: IndexPath)
}
你应该在你的单元类代码中添加这样的东西
class YourCell: UITableViewCell {
weak var delegate: ButtonCellDelegate?
var indexPath: IndexPath?
...
@IBAction func buttonPressed() {
if let indexPath = indexPath, let delegate = delegate {
delegate.didPressButtonInCellAt(indexPath)
}
}
}
而实现本身是:
class YourTableViewController: UITableViewController, ButtonCellDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.delegate = self
cell.indexPath = indexPath
...
}
func didPressButtonInCellAt(_ indexPath: IndexPath) {
//Things you want to do, if a button is pressed
}
}
但是如果你仍然想使用标签,你可以使用sender传递它们
class YourTableViewController: UITableViewController {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.button.tag = indexPath.row
...
}
@IBAction func buttonPressed(sender: UIButton) {
let row = sender.tag
//Things you want to do, if a button is pressed
}
}
使用委托是处理此类问题的更稳健的方式,因为它可以轻松处理多节表视图并且更易于维护。
如果您的按钮是通过编程方式创建的,您可以添加如下操作:
//YourCell
override func awakeFromNib() {
super.awakeFromNib()
let button = UIButton() //replace with your initialization
button.addTarget(self, action: #selector(pressed(sender:)), for: .touchUpInside)
}
func pressed(sender: UIButton!) {
if let indexPath = indexPath, let delegate = delegate {
delegate.didPressButtonInCellAt(indexPath)
}
}
如果你还想使用标签,你只需要在viewDidLoad中使用addTarget就可以了