在Swift中改变VC问题。 如何在标签栏控制器中的视图之间传递数据?

我有四个ViewController,我不使用UITabbedbar,因为这是更难以定制。 我使用模态赛格,但我认为内存消耗是过度的。 这是我的第一个和第二个VC的屏幕截图。 我必须使用正确的更改视图?

在这里输入图像说明


这是我使用的代码:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if (segue.identifier == "second") { let secondVC = segue.destinationViewController as SecondViewController; } } 

从Storyboard图中,显然你已经从“标签栏”中的每个button到另一个视图控制器创build了一个segue。 除了unwind segue之外 ,segues总是创build一个他们正在切换的视图控制器的新实例。 所以,如果你使用你的设置从视图控制器1切换到视图控制器2,然后回到视图控制器1,你将不会返回到你来自的视图控制器,而是你将创build一个全新的视图控制器1。

这就是为什么你的内存消耗是过度的。 你不断创build视图控制器,直到你的应用程序崩溃。

我会build议你回到使用标签栏控制器。 它们被devise成一次分配视图控制器,然后在它们之间切换。 此外,他们有一个标准的外观原因,它可以帮助您的应用程序的用户立即知道如何与他们进行交互。


要在选项卡之间传递数据,您将不会使用segues,因为切换选项卡时不会发生segue。 有很多方法可以做到这一点,但是他们都归结为模型数据存储在所有标签可以访问的地方。 这可以在更大的应用程序中使用CoreData来完成。 对于一个简单的应用程序,你可以做到以下几点:

  1. 创build一个UITabBarController的自定义子类。 我们称之为CustomTabBarController 。 让该类创build并保存将由每个选项卡访问的模型数据。

    CustomTabBarController.swift:

     import UIKit // This class holds the data for my model. class ModelData { var name = "Fred" var age = 50 } class CustomTabBarController: UITabBarController { // Instantiate the one copy of the model data that will be accessed // by all of the tabs. var model = ModelData() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } 
  2. 在您的Storyboard中,在Identity Inspector中,将UITabBarController的类更改为CustomTabBarController

    在这里输入图像说明

  3. viewWillAppear的每个选项卡中,获取对模型数据的引用,然后可以使用它。

    FirstViewController.swift:

     import UIKit class FirstViewController: UIViewController { override func viewWillAppear(animated: Bool) { // Get a reference to the model data from the custom tab bar controller. let model = (self.tabBarController as CustomTabBarController).model // Show the we can access and update the model data from the first tab. // Let's just increase the age each time this tab appears and assign // a random name. model.age++ let names = ["Larry", "Curly", "Moe"] model.name = names[Int(arc4random_uniform(UInt32(names.count)))] } } 

    SecondViewController.swift:

     import UIKit class SecondViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ageLabel: UILabel! override func viewWillAppear(animated: Bool) { // Get a reference to the model data from the custom tab bar controller. let model = (self.tabBarController as CustomTabBarController).model // This tab will simply access the data and display it when the view // appears. nameLabel.text = model.name ageLabel.text = "\(model.age)" } }