ios - 在 swift 3 中创建 View Controller 的单例

标签 ios swift singleton viewcontroller

我知道如何在 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/

相关文章:

javascript - 在 CoffeeScript 中为我的单例类定义属性 getter

c# - 使用静态事件或通过单例订阅的事件订阅?

ios - 动画时无法同时满足约束

ios - 子类 UIView,当设置为 Storyboard中的默认 View 时,编译器无法识别而不进行强制转换

ios - 无法将类型 'Authorize.ClubsViewController' (0x109c70cc8) 的值转换为 'Authorize.NewViewController' (0x109c70df8)

swift - PromiseKit 语法链 swift

c++ - 需要在 Singleton 类中私有(private)化赋值运算符

ios - 带顶部对齐的 Watchkit 多行标签

python - Pusher:Swift (iOS) 发布者/服务器到 Raspberry Python 订阅者/客户端

ios - 从 JSON API 附加到数组