简体   繁体   English

如何在swift中创建UIView单例?

[英]How to create a UIView singleton in swift?

I want to avoid create UIView like This: 我想避免像这样创建UIView:

let singleView = SingleView()

Here is How I create a SingleTon: 以下是我如何创建SingleTon:

class SingleView:UIView {

    static let sharedInstance = SingleView()

    private init() {
        super.init(frame:CGRectZero)
    }

    override init(frame:CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

However it will compile sucess. 但是它会编译成功。

First of all, a view singleton is a bad idea, because a UIView instance will only have one superView , eg be subView of only one other view. 首先,视图单例是一个坏主意,因为UIView实例只有一个superView ,例如只有一个其他视图的子视图。

  • If you use this only once, there is no benefit from sharing the instance. 如果您只使用一次,则共享实例没有任何好处。
  • If you use it in different UIViewController instances, it will probably not behave as you expect. 如果您在不同的UIViewController实例中使用它,它可能不会按预期运行。

Anyhow, you seem to not even want a singleton, which is good. 无论如何,你似乎甚至不想要单身,这很好。

So, how about this? 那么,这个怎么样?

class SingleView:UIView {
    init() {
        super.init(frame:CGRectZero)
    }

    override init(frame:CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

Now you can initialize without parameters in the constructor like you wanted all along. 现在你可以在构造函数中初始化没有参数,就像你一直想要的那样。

PS: please note that constructors in swift always create new instances (or none at all). PS:请注意,swift中的构造函数总是创建新实例(或根本没有)。 If you want to use a singleton, you hide the constructors and provide a factory-method (or a static let as you did). 如果要使用单例,则隐藏构造函数并提供工厂方法(或者像您一样提供static let )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM