在视图控制器之间关闭之前,通过委托协议传递数据

时间:2018-11-08 00:20:40

标签: swift xcode delegates protocols dismiss

我有一个很快的4个问题,希望有人知道答案,因为Google不会...

我有2个ViewController, 第一个控制器像这样加载第二个控制器:

//视图控制器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)
  }
}

//视图控制器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)

    }
}

// 因此我尝试创建一个协议,然后在关闭之前传递数据,但这似乎不起作用。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

您没有使用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)
}

将实例化的视图控制器投射到DatePopupViewController上,以访问集合dataDelegate