Dejauu
Dejauu

Reputation: 129

How to create a UIView singleton in swift?

I want to avoid create UIView like This:

let singleView = SingleView()

Here is How I create a 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.

Upvotes: 4

Views: 3812

Answers (1)

Tobi Nary
Tobi Nary

Reputation: 4596

First of all, a view singleton is a bad idea, because a UIView instance will only have one superView, e.g. be subView of only one other view.

  • 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.

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). If you want to use a singleton, you hide the constructors and provide a factory-method (or a static let as you did).

Upvotes: 1

Related Questions