我有一个带有四个 View Controller 的应用程序。 1、2 和 3 之间的导航很好,但从 View Controller 1 中,您可以选择转到 2 或 4(这是我的设置)。我有一个从 1 到 4 的转场。然后我使用展开转场返回。但是当我使用 segue 返回 4 时,它会实例化 4 的新实例。
我的问题:有没有办法访问用户上次拥有的 View Controller 的同一实例。
最佳答案
就像@Paul11在评论中所说的那样,如果您希望访问相同的实例,您应该保留尝试推送的UIViewController
的引用
举个例子
var someViewController = SomeViewController() // << this is at the class level scope
func someSampleFunc() {
// doing this would create a new instance of the `SomeViewController` every time you push
self.navigationController?.pushViewController(SomeViewController(), animated: true)
// whereas if you use the variable which is at the class level scope the memory instance is kept
self.navigationController?.pushViewController(someViewController, animated: true)
}
另一个例子
class Bro {
var name = "Some Name"
func sayDude() {
// since `name` is a class level you can access him here
let dude = "DUUUUUUUDE" // this variable's lifetime only exists inside the `sayDude` function, therefore everytime you call `sayDude()` a new instance of `dude` is created
print(name)
print(dude)
}
func doBackflip() {
sayDude() //
print(name + " does backflip") // since `name` is a class level you can access him here
}
}
关于ios - segue 创建 View Controller 的新实例 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43443170/