gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:59:55 25 4
gpt4 key购买 nike

我有像测验这样的表格 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com