我有四个 ViewController,我不使用 UITabbedbar,因为它更难以定制。
我使用模态转场,但我认为内存消耗过多。
这是我的第一个和第二个 VC 的屏幕截图。
我必须使用什么才能正确更改视图?
这就是我使用的代码:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "second") {
let secondVC = segue.destinationViewController as SecondViewController;
}
}
从故事板图中可以清楚地看出,您已经创建了从“选项卡栏”中的每个按钮到另一个视图控制器的 Segue。除了放松继续,segues 总是创建它们要切换到的视图控制器的新实例。因此,如果您使用设置从视图控制器 1 切换到视图控制器 2,然后返回视图控制器 1,您将不会返回到原来的视图控制器,而是将创建一个全新的视图控制器 1。
这就是你的内存消耗过多的原因。您不断创建视图控制器,直到您的应用程序崩溃。
我建议您重新使用标签栏控制器。它们被设计为预先分配视图控制器一次,然后在它们之间切换。此外,它们具有标准外观是有原因的,它可以帮助您的应用程序的用户立即知道如何与它们交互。
要在选项卡之间传递数据,您不会使用 Segue,因为切换选项卡时不会发生 Segue。有很多方法可以做到这一点,但它们都归结为将模型数据存储在所有选项卡都可以访问的位置。这可以通过以下方式完成CoreData在更大的应用程序中。对于一个简单的应用程序,您可以执行以下操作:
-
创建一个自定义子类UITabBarController
。我们就这样称呼它吧CustomTabBarController
。让该类创建并保存每个选项卡将访问的模型数据。
自定义 TabBarController.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.
}
}
-
在 Storyboard 的 Identity Inspector 中,更改UITabBarController
to CustomTabBarController
.
-
In viewWillAppear
在每个选项卡中,获取对模型数据的引用,然后就可以使用它。
第一个 ViewController.swift:
import UIKit
class FirstViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Get a reference to the model data from the custom tab bar controller.
let model = (self.tabBarController as! CustomTabBarController).model
// Show that 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 += 1
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) {
super.viewWillAppear(animated)
// 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)"
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)