独自の初期化をするつもりがなくても init:frame:
と init:coder
はoverride必須らしい。
// これだけ必要
class MyButton : UIButton{
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
イニシャライザの定義には何か制限があるみたい?
ダメな例
init(title: String){
super.init(type: .System)
}
//これは下記のエラーになる
// Must call a designated initializer of the superclass 'UIButton'
OKな例
init(frame:CGRect, title: String){
super.init(frame:frame)
self.setTitle(title, forState: .Normal)
}
//あるいは
init(title: String){
super.init(frame: CGRectZero)
self.setTitle(title, forState: .Normal)
}
UIView のサブクラスは init:frame
を呼ばなくてはいけない的な制限があるようです。
ちなみに iOS View
プログラミングガイド の 「ビューのサブクラスの初期化」 には下記の記述があります。
カスタムビューの初期化
新規に定義するビューオブジェクトには、それぞれカスタムのinitWithFrame:初期化メソッドを含 める必要があります。このメソッドは、作成時にクラスを初期化し、ビューオブジェクトを既知の状 態に設定します。ビューのインスタンスをコード内でプログラムによって作成する場合は、このメ ソッドを使用します。