【问题标题】:Passing data to another ViewController without moving to the ViewController在不移动到 ViewController 的情况下将数据传递给另一个 ViewController
【发布时间】:2017-06-24 20:52:20
【问题描述】:

我有一个使用不同视图控制器的注册流程。我从 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。我如何做到这一点?

【问题讨论】:

    标签: ios swift uiviewcontroller


    【解决方案1】:

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

    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"
    

    并在你的 FifthViewController 中像这样使用

      let singleTon = SingletonClass()
      print(singleTon.sharedInstance.dataText)
    

    【讨论】:

      【解决方案2】:

      在你的 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)'
      

      【讨论】:

      • 这只有在我想从发送数据的地方推送视图控制器时才有效。我不想那样做。
      猜你喜欢
      • 2016-05-07
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多