我知道如何在 swift 中创建单例类。创建单例类的最好和最简单的方法如下:
class Singleton {
static let sharedInstance = Singleton()
}
但是我不需要任何普通类的单例。我需要为 viewcontroller 类创建单例。所以我正在使用这段代码创建单例
class AViewController:UIViewController {
static let sharedInstance = AViewController()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
它在 AViewController()
附近给我错误
Missing argument for parameter 'coder' in call
看起来它想让我用 init(coder: NSCoder)
初始化。但是我应该通过 coder
传递什么参数或值?
最佳答案
如果你真的想为某个场景对应的 View Controller 使用单例,你可能会这样做:
class SecondViewController: UIViewController {
static let shared = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Foo")
}
在这个例子中, Storyboard是Main.storyboard
,相关场景的 Storyboard标识符是Foo
。显然,将这些值替换为适合您的情况的任何值。
然后调用它的其他 View Controller 可以做类似的事情:
@IBAction func didTapButton(_ sender: Any) {
let controller = SecondViewController.shared
show(controller, sender: self)
}
我不建议 View Controller 使用单例。 View Controller (及其 View )应该在需要时创建,并在它们被关闭时被允许释放。而且您正在失去许多 Storyboard的好处(通过它您可以看到场景之间的逻辑流程以及它们之间的 segues)。而且,如果你在不同的上下文中使用这个 View Controller ,你就会引发问题,这些问题源于 View Controller 层次结构与 View 层次结构不同步。我真的不鼓励您将单例用于 View Controller 。
但如果你打算这样做,你可以做类似的事情......
关于ios - 在 swift 3 中创建 View Controller 的单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41136597/