ios - 确定在哪个 TableView 中按下了单元格按钮?

标签 ios swift uitableview

我有表格 View 单元格,例如测验。在每个单元格中我都有一个按钮,我如何识别按下了哪个单元格按钮。也许通过 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

}

这是它在 Storyboard中的样子:enter image description here

最佳答案

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

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)")
        }
    }    
}

关于ios - 确定在哪个 TableView 中按下了单元格按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114305/

相关文章:

ios - 如何解决 Cocoapods lint 命令中的链接器错误?

ios - Lockito 类应用程序,用于在 iOS 上模拟/伪造位置

ios - 计时器被触发两次但未被取消

ios - SwipeCellKit 滑动删除未调用

swift - 滑动时切换 TableViewCell 中框的颜色

ios - 在 iOS 中对包含字母数字单词的数组进行排序

iphone sqlite 问题

swift - 按钮图像不会立即刷新

swift - 查找标注 MapKit 的索引

ios - fatal error : unexpectedly found nil while unwrapping an Optional value - when UITextField is tapped