You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift代理未触发:点击Save按钮如何触发Cell的mainSaveTapped方法

问题解决方案

问题根源

你的代码里AddQuestionViewController的delegate属性始终是nil,没有关联到MultipleAnswerTableViewCell实例,所以点击saveTapped时调用delegate?.mainSaveTapped()不会触发任何逻辑。虽然MultipleAnswerTableViewCell遵守了AddQuestionViewControllerDelegate协议,但两者之间没有建立委托关系。

解决方法

方法一:建立委托关联(适合单个多选答案单元格场景)

修改AddQuestionViewController中的configureMultiAnswerCell方法,将当前单元格设置为VC的委托对象:

func configureMultiAnswerCell(indexPath: IndexPath) -> MultipleAnswerTableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
    cell.parentVC = self
    cell.answerDelegate = self
    self.delegate = cell // 关键:把VC的委托指向当前多选单元格
    cell.setupMultipleAnswerView()
    return cell
}

这样点击saveButton时,delegate?.mainSaveTapped()就会调用到MultipleAnswerTableViewCell中的对应方法。

方法二:直接定位单元格并调用方法(更通用,支持多个多选单元格)

如果页面中有多个多选答案单元格,或者不想依赖委托模式,可以直接在saveTapped方法中找到目标单元格并调用方法:

@IBAction func saveTapped(_ sender: UIButton) {
    // 遍历所有cell类型,找到多选答案对应的行
    for (index, cellType) in cellTypes.enumerated() {
        if cellType == .multiAnswer {
            let indexPath = IndexPath(row: index, section: 0)
            if let multiCell = tableView.cellForRow(at: indexPath) as? MultipleAnswerTableViewCell {
                multiCell.mainSaveTapped()
            }
        }
    }
}

这种方式跳过了委托环节,直接定位到目标单元格执行逻辑,更直观。

内容的提问来源于stack exchange,提问作者Mert Köksal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:05:20