如何在关闭 ViewController 时将数据传递给另一个控制器? [英] How to pass data to another controller on dismiss ViewController?

查看:20
本文介绍了如何在关闭 ViewController 时将数据传递给另一个控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 VC 关闭时将我的数据从一个 ViewController 传递到另一个 VC.可能吗?

I want to pass my data from one ViewController to another VC on VC dismiss. Is it possible?

我尝试了下一个方法,但没有成功:

I've tried the next method and no success:

点击按钮:

self.dismiss(animated: true) { 
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "EditViewController") as! EditViewController
        controller.segueArray = [values]
    }

EditViewController 再次出现时,我的 segueArraynil .

when EditViewController appears again, my segueArray is nil there.

如何在解除时将数据从 my ViewController 传递到 EditViewController?

How can I pass my data from my ViewController to the EditViewController on dismiss?

推荐答案

将数据传回上一个视图控制器的最佳方式是通过委托...当从 ViewController A 到 B 时,将视图控制器 A 作为委托传递在 ViewController B 的 viewWillDisappear 方法上,调用 ViewController A 中的委托方法.这是一个简单的例子:

The best way to pass data back to the previous view controller is through delegates... when going from ViewController A to B, pass view controller A as a delegate and on the viewWillDisappear method for ViewController B, call the delegate method in ViewController A.. Protocols would help define the delegate and the required methods to be implemented by previous VC. Here's a quick example:

传递数据的协议:

protocol isAbleToReceiveData {
  func pass(data: String)  //data: string is an example parameter
} 

视图控制器 A:

class viewControllerA: UIViewController, isAbleToReceiveData {

  func pass(data: String) { //conforms to protocol
  // implement your own implementation
   }

  prepare(for: Segue) {
    /** code for passing data **/
    let vc2 = ViewCOntrollerB()  /
    vc2.delegate = self   //sets the delegate in the new viewcontroller 
                          //before displaying
    present(vc2)
  }
}

关闭视图控制器:

class viewControllerB: UIViewController {

  var delegate: isAbleToReceiveData

  viewWillDisappear {
      delegate.pass(data: "someData") //call the func in the previous vc
  }
}

这篇关于如何在关闭 ViewController 时将数据传递给另一个控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆