9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

インスタンス単位で一度だけ実行したい初期化コードの考察

Last updated at Posted at 2016-03-19

UIView などでインスタンス単位で一度だけ実行したい初期化コードの考察 - Qiita

上記の記事を拝見して、少し変更してみました。

    lazy var setup: (()->())? = {
        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "panGesture:")
        self.addGestureRecognizer(panGestureRecognizer)
        self.setup = nil
    }

lazyであってもvarには再代入が可能なので、自己を破棄するコードをsetupの最終行に仕込んでいます。

呼び出しは以下のみで、元記事のようにif分にする必要はありません。

setup?()

元記事のようにlayoutSubviewsで実行する場合は以下のようになります。

class MyView: UIView {
    override func layoutSubviews() {
        super.layoutSubviews()
        setup?()
    }
9
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?