StackView Subviews Resets To Zero

Viewed 20

I have an actionForAddAnswer button and when on tapped calls func addViewToStackView. When tapped on the button it adds another stack inside the surveyStackView. It adds inside the addViewToStackView() func but inside the other func it resets to zero and can not reach to its text field.

func mainSaveTapped is triggered from another class hence it does not know this class's surveyStackView. I guess because of that stack inside the mainSaveTapped always appears nil and I get Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value:

How can I save and share my surveyStackView to mainSaveTapped func so it can see all the values and text inside?

class MultipleAnswerTableViewCell: UITableViewCell {

@IBOutlet weak var surveyStackView: UIStackView!
var stackView: UIStackView!
var parentVC: AddQuestionViewController!

private func addViewToStackView() {
        let answerSurveyView: SurveyAnswerView = SurveyAnswerView()
        answerSurveyView.delegate = self
        answerSurveyView.answerTextField.delegate = self
        answerSurveyView.answerTextField.placeholder = ""
        answerSurveyView.answerTextField.backgroundColor = .clear
        answerSurveyView.answerTextField.layer.cornerRadius = 4
        answerSurveyView.answerTextField.attributedText = NSAttributedString(
            string: "",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.black,
                         NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14),
                         NSAttributedString.Key.kern: -0.14
                        ]
        )
        answerSurveyView.answerTextField.tag = answerTag
        answerSurveyView.tag = answerTag
        answerTag = answerTag + 1
        surveyStackView.addArrangedSubview(answerSurveyView)
        surveyStackView.axis = .vertical
        surveyStackView.distribution = .fillEqually
        surveyStackView.translatesAutoresizingMaskIntoConstraints = false
        stackViewHeigthConstraint.constant = CGFloat(surveyStackView.arrangedSubviews.count * 55)
        //        to save surveyStackView when save button tapped
        stackView = surveyStackView
    }



func mainSaveTapped() {
        let text = checkPostShare(stack: stackView)
 }


private func checkPostShare(stack: UIStackView) -> String? {
            let views = stack.arrangedSubviews
                for subview in views {
                    let textfield = subview.subviews[0] as? UITextField
                    if let answer = textfield?.text {
                       checkAnswer(textField: textfield!)
         }
    }

And the class that triggers mainSaveTapped func is

class AddQuestionViewController: BaseViewController {

@IBAction func saveTapped(_ sender: UIButton) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
        cell.mainSaveTapped()
 }
}
0 Answers
Related