LoginSignup
2
0

More than 5 years have passed since last update.

UIViewにはconvenience initializerが存在する - UIView has a convenience initializer.

Last updated at Posted at 2018-06-18

疑問

UIViewを拡張して、

class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    func commonInit() {
    }
}

こういうViewを作って、CustomView()と引数なしの初期化を行うと、override init(frame: CGRect)で定義したイニシャライザが呼ばれ、commonInit()も期待通りに呼ばれるのはなぜだろうと、ふと疑問に思った。

検証

UIViewがconvenience initializerを持っていると考えると説明がつく。


class UIViewLike {
    init(frame: CGRect) {
        print("UIViewLike initialized")
    }

    convenience init() {
        self.init(frame: .zero)
    }
}

class CustomViewLike: UIViewLike {
    override init(frame: CGRect) {
        super.init(frame: frame)
        print("CustomViewLike initialized")
    }
}

これらを定義して、

let hoge = CustomViewLike()

と引数なしのイニシャライザを呼んでやると、

UIViewLike initialized
CustomViewLike initialized

とログに表示される。

2
0
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
2
0