Can't Call ParentVC Func Swift

Viewed 36

This Cell can not call parentVC's function.

 class MultipleAnswerTableViewCell: UITableViewCell, SurveyAnswerViewDelegate, UITextFieldDelegate {

var parentVC: AddQuestionViewController!

 let surveyAnswer = SurveyAnswer(answer: textField.text!, order: Int(textField.tag))
            surveyAnswers.append(surveyAnswer)
            self.parentVC?.savedAnswer(answer: surveyAnswer). //Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file Rtuk/MultipleAnswerTableViewCell.swift

 if let myParentVC = self.parentVC as? AddQuestionViewController {
                myParentVC.savedAnswer(answer: surveyAnswer)
            }

And the ParentVC is

class AddQuestionViewController: BaseViewController, SurveyTopTableViewCellDelegate, MultipleAnswerTableViewCellDelegate, SurveyTextAnswerTableViewCellDelegate, UITextFieldDelegate {

 func configureMultiAnswerCell(indexPath: IndexPath) -> MultipleAnswerTableViewCell {
        let postSettingsVC = PostSettingsViewController.instantiateFrom(appStoryboard: .Post)
        postSettingsVC.post = post
        let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
        cell.parentVC = self
        return cell
    }

 func savedAnswer(answer: SurveyAnswer) {
        self.surveyAnswers.append(answer)
        print("answerLo", answer.answer)
    }



func configureTable() {
        tableView.register(MultipleAnswerTableViewCell.self)
        }

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

func pickerChanged(type: SurveyType) {
        switch type {
        case .multiAnswer: cellTypes = [.fixedTop, .multiAnswer]
        case .singleAnswer: cellTypes = [.fixedTop, .singleAnswer]
        case .textAnswer: cellTypes = [.fixedTop, .textAnswer]
        }
    }

Somehow child never reaches to parentVC. How I configure tableview is added

I am not sure but maybe this func inside ParentVC may break it.

 @IBAction func saveButtonTapped(_ sender: UIButton) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
        cell.mainSaveTapped(stackView: savedStack)
    }
1 Answers

Change your method like that to make it work. But, as I mentioned in comments above, it is very strange implementation and u should think about its improvement)

   @IBAction func saveButtonTapped(_ sender: UIButton) {
        let cell = tableView.visibleCells.first(where: { $0 is MultipleAnswerTableViewCell }) as? MultipleAnswerTableViewCell
        cell?.mainSaveTapped(stackView: savedStack)
    }
Related