确定在哪个表格视图中按下了“单元格”按钮?

Аза*_*нов -1 uitableview ios swift

我有像测验一样的表格视图单元格。在每个单元格中都有一个按钮,以及如何确定在哪个单元格中按下了按钮。也许通过IndexPath ???这就是我将按钮连接到的方式

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionCell")!
     variant1 = cell.contentView.viewWithTag(1) as! UIButton
     variant2 = cell.contentView.viewWithTag(2) as! UIButton
     variant3 = cell.contentView.viewWithTag(3) as! UIButton
     variant4 = cell.contentView.viewWithTag(4) as! UIButton

    variant1.addTarget(self, action: #selector(self.variant1ButtonPressed), for: .touchUpInside)
    variant2.addTarget(self, action: #selector(self.variant2ButtonPressed), for: .touchUpInside)
    variant3.addTarget(self, action: #selector(self.variant3ButtonPressed), for: .touchUpInside)
    variant4.addTarget(self, action: #selector(self.variant4ButtonPressed), for: .touchUpInside)

    return cell
}

func variant1ButtonPressed() {
    print("Variant1")
    variant1.backgroundColor = UIColor.green


}
func variant2ButtonPressed() {
    print("Variant2")
    variant2.backgroundColor = UIColor.green


}
func variant3ButtonPressed() {
    print("Variant3")
    variant3.backgroundColor = UIColor.green

}
func variant4ButtonPressed() {
    print("Variant4")
    variant4.backgroundColor = UIColor.green

}
Run Code Online (Sandbox Code Playgroud)

这是情节提要中的样子: 在此处输入图片说明

Mic*_*ień 5

您应该使用委托模式,基本示例:

protocol MyCellDelegate {
    func didTapButtonInside(cell: MyCell)
}

class MyCell: UITableViewCell {

    weak var delegate: MyCellDelegate?

    func buttonTapAction() {
        delegate?.didTapButtonInside(cell: self)
    }
}

class ViewController: MyCellDelegate {

    let tableView: UITableView

    func didTapButtonInside(cell: MyCell) {
        if let indexPath = tableView.indexPath(for: cell) {
            print("User did tap cell with index: \(indexPath.row)")
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)