将数据传递到另一个ViewController而不移动到ViewController

时间:2017-06-24 12:02:57

标签: ios swift uiviewcontroller

我有一个使用不同视图控制器的注册流程。我从ViewController1中的用户那里获取输入,移动到下一个视图控制器(ViewController2),并将数据传递给最后一个视图控制器(例如ViewController5)。

问题是我可以将数据传递给下一个视图控制器,但我无法将其传递给最后一个视图控制器,如:

// Move to Second View of the flow.
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: “SecondViewController“) as! SecondViewController
secondViewController.dataText = dataText!
self.navigationController?.show(secondViewController, sender: nil)

// Pass the data to the last View of the flow.
let fifthViewController = self.storyboard?.instantiateViewController(withIdentifier: “FifthViewController“) as! FifthViewController
fifthViewController.dataText = emailText!

dataText会传递给SecondViewController但不传递给FifthViewController。我如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

您可以使用类并创建单例对象来存储数据并进行检索 在第五个视图控制器

class SingletonClass {
    var sharedInstance: SingletonClass {
          struct Static {
               static let instance = SingletonClass()
          }
          return Static.instance
     }
     var dataText : String = ""
}

现在您可以将数据存储在单个对象中,如下所示

 let singleTon = SingletonClass()
 singleTon.sharedInstance.dataText = "store data"

并在你的第五个ViewController

中使用这个
  let singleTon = SingletonClass()
  print(singleTon.sharedInstance.dataText)

答案 1 :(得分:0)

在你的Appdelegate.swift文件中,像这样创建一个FifthViewController实例

'var fifthViewController: FifthViewController?'

在您想要传递数据的视图控制器中

'let appDelegate = UIApplication.shared.delegate as! AppDelegate'

appDelegate.fifthViewController = self.storyboard?.instantiateViewController(withIdentifier: “ FifthViewController“) as! FifthViewController
appDelegate.fifthViewController.dataText = emailText!

什么时候你想推送FifthViewController使用这个控制器的Appdelegte引用像这样

'self.navigationController?.pushViewController(appDelegate.fifthViewController!, animated: true)'