Home > Software engineering >  Protocol Delegate Does not Trigger Swift
Protocol Delegate Does not Trigger Swift

Time:09-16

I want to trigger MultipleAnswerTableViewCell's mainSaveTapped func when the IBAction saveButton tapped.

Here is my class with the protocol

protocol AddQuestionViewControllerDelegate: AnyObject {
    func mainSaveTapped()
}

class AddQuestionViewController: BaseViewController, MultipleAnswerTableViewCellDelegate, UITextFieldDelegate {

weak var delegate: AddQuestionViewControllerDelegate?

 @IBAction func saveTapped(_ sender: UIButton) {
        delegate?.mainSaveTapped()
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch cellTypes[indexPath.row] {
    case .fixedTop: return configureFixedTop(indexPath: indexPath)
    case .multiAnswer: return configureMultiAnswerCell(indexPath: indexPath)
    case .singleAnswer: return configureSingleAnswerCell(indexPath: indexPath)
    case .textAnswer: return configureTextAnswerCell(indexPath: indexPath)
    }
}



func configureMultiAnswerCell(indexPath: IndexPath) -> MultipleAnswerTableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
        cell.parentVC = self
        cell.answerDelegate = self
        cell.setupMultipleAnswerView()
        return cell
    }

And this is my MultipleAnswerTableViewCell

protocol MultipleAnswerTableViewCellDelegate: AnyObject {
    func sendAnswers(surveyAnswers: [SurveyAnswer])
}

class MultipleAnswerTableViewCell: UITableViewCell, AddQuestionViewControllerDelegate, UITextFieldDelegate {

weak var answerDelegate: MultipleAnswerTableViewCellDelegate?

 func mainSaveTapped() {
        checkPostShare()
    }

My func mainSaveTapped never triggered hence checkPostShare never called. What should I do to trigger mainSaveTapped func inside the MultipleAnswerTableViewCell

CodePudding user response:

You don't assign a value to the delegate property inside the vc

weak var delegate: AddQuestionViewControllerDelegate?

So here delegate? is nil

@IBAction func saveTapped(_ sender: UIButton) {
    delegate?.mainSaveTapped()  // delegate? is nil
}

You need to send a message from the vc to the cell , here you don't need a delegate ,instead

 @IBAction func saveTapped(_ sender: UIButton) { 
   (tableView.visibleCells as? [MultipleAnswerTableViewCell])?.forEach { cell in
     cell.mainSaveTapped()
   } 
}
  • Related