您可以使用 DELEGATE PATTERN 传回数据:
以下是关于两个视图控制器之间的委托的一点帮助:
第 1 步:在 UIViewController 中创建一个协议,您将删除/发送数据。
protocol FooTwoViewControllerDelegate:class {
func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}
Step2:在发送类(即UIViewcontroller)中声明委托
class FooTwoViewController: UIViewController {
weak var delegate: FooTwoViewControllerDelegate?
[snip...]
}
第三步:在类方法中使用委托将数据发送给接收方法,接收方法可以是任何采用协议的方法。
@IBAction func saveColor(_ sender: UIBarButtonItem) {
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}
第四步:在接收类中采用协议
class ViewController: UIViewController, FooTwoViewControllerDelegate {
第 5 步:实现委托方法
func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " + text
controller.navigationController.popViewController(animated: true)
}
第 6 步:在 prepareForSegue 中设置委托:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! FooTwoViewController
vc.colorString = colorLabel.text
vc.delegate = self
}
}
这应该可行。这当然只是代码片段,但应该给你的想法。有关此代码的详细说明,您可以在此处转到我的博客条目:
segues and delegates
如果您对我在此处写过的代表的幕后情况感兴趣:
under the hood with delegates
original answer