Search code examples
swiftprotocolsparent

Protocol Doesn't Send Value to Other VC


That is my footerView called FooterTableViewCell. I have this protocol called SurveyAnswerTableViewCellDelegate. It's parent is AddQuestionViewController.

When I tap on the footerView I trigger @IBActtion.

@objc protocol SurveyAnswerTableViewCellDelegate: AnyObject {
    func textSaved(_ text: String)
}

class FooterTableViewCell: UITableViewHeaderFooterView {
var parentVC: AddQuestionViewController!

@IBAction func addNewTapped(_ sender: Any) {
        print("tapped")
        let newTag = model.tag + 1
        parentVC.addNewAnswer()
    }

This button action triggers AddQuestionViewController

class AddQuestionViewController: SurveyAnswerViewDelegate, UITextFieldDelegate, UITableViewDelegate, SurveyAnswerTableViewCellDelegate {
    var answers: [SurveyAnswerModel] = []
    var savedText : String = ""
    static var delegate: SurveyAnswerTableViewCellDelegate?

I try creating an empty string and append a new answer to my array. But this text here is always "".

func addNewAnswer() {
        let newAnswer = SurveyAnswerModel(answer: savedText, tag: 0)
        self.answers.append(newAnswer)
        self.tableView.reloadData()
    }
    
    func textSaved(_ text: String) {
         savedText = text
    }

The textfield I try to read is inside SurveyAnswerTableViewCell while setting up the cell inside the tableview I call setup function.

class SurveyAnswerTableViewCell: UITableViewCell {
    @IBOutlet weak var textField: UITextField!
    weak var delegate: SurveyAnswerTableViewCellDelegate?
    var parentVC: AddQuestionViewController!

func setup() {
        if let text = self.textField.text {
            self.delegate?.textSaved(textField.text!)
        }
    }

extension AddQuestionViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(forIndexPath: indexPath) as SurveyAnswerTableViewCell
        cell.parentVC = self
        cell.setup()
        return cell
    }

How can I successfully send that text to AddQuestionViewController so it appends a new answer with correct string


Solution

  • Here's what it looks like is happening:

    1. Button tapped
    2. addNewTapped(_:) invoked
    3. addNewAnswer() invoked
    4. newAnswer is appended to answers
    5. tableView.reloadData() invoked
    6. Cells are regenerated with new/empty textfields (so delegate.textSaved is never invoked)

    so I'm not sure what you're trying to do, but here's what I figure are a couple possible routes:

    • store UITextFields separately and add them into table cells so they're not removed by a table reload
    • conform AddQuestionViewController to UITextFieldDelegate and set it as the textfields' delegate to observe textfield texts changing (and if you're only using 1 textfield, you could set savedText there)