ios - 确定在哪个表格 View 中按下了 Cell 按钮?

标签 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 - 确定在哪个表格 View 中按下了 Cell 按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45073556/

相关文章:

ios - 我如何快速访问函数数组?

swift - Swift 中的 NSUserDefaults - 实现类型安全

ios - 如何自定义UITableViewCell的插入删除控件?

swift - Xcode Storyboard 类没有模块

ios - 在不同的collectionView单元格内填充不同的tableView

ios - 关于如何显示用户评论列表的想法(UITableView vs UIScrollView vs?)

iphone - CATransform3DTranslate和CATransform3DScale之间的区别

ios - 用于打开商店的模型与用于创建商店的模型不兼容

ios - iPad 应用程序,如何在 uiviewcontroller 之上显示 uiviewcontroller

ios - 我怎样才能拍照并预览