passing data via delegate protocols before dismiss between view controllers

I have a swift 4 question, hopefully someone knows the answer, because google does not...

I have 2 ViewControllers, first controller loads up the second one like this:

// view controller 1:

class ViewController: UIViewController,UITextFieldDelegate,popupDelegate {

  func pass_data(updated: String) {
    print(updated)
  }

  func textFieldDidBeginEditing(_ textField: UITextField) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let ivc = storyboard.instantiateViewController(withIdentifier: "calendar_view")
    ivc.modalTransitionStyle = .crossDissolve
    self.present(ivc, animated: true)
  }
}

// view controller 2:

protocol popupDelegate {
  func pass_data(updated: String)
}

class DatePopupViewController: UIViewController {

  var dataDelegate: popupDelegate?

  @IBAction func cal_save_data(_ sender: UIButton) {
      // save data here
      dataDelegate?.pass_data(updated:"pass data from vc2")

      let transition: CATransition = CATransition()
      transition.duration = 0.2
      transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
      transition.type = CATransitionType.fade
      transition.subtype = CATransitionSubtype.fromBottom
      self.view.window!.layer.add(transition, forKey: nil)
      self.dismiss(animated: false, completion: nil)

    }
}

// so I tried creating a protocol, then passing the data before dismiss, but it seems to not work. what am I doing wrong ?

1 answer

  • answered 2018-11-08 00:38 Callam

    You're not setting the delegate of the newly instantiated controller with icv.dataDelegate = self

    func textFieldDidBeginEditing(_ textField: UITextField) {
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let ivc = storyboard.instantiateViewController(withIdentifier: "calendar_view") as! DatePopupViewController
    
        ivc.modalTransitionStyle = .crossDissolve
        icv.dataDelegate = self
    
        self.present(icv, animated: true)
    }
    

    Cast the instantiated view controller to a DatePopupViewController to access set dataDelegate.