LoginSignup
7
7

More than 5 years have passed since last update.

UIButton のサブクラスを作る

Last updated at Posted at 2015-12-25

独自の初期化をするつもりがなくても 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:初期化メソッドを含 める必要があります。このメソッドは、作成時にクラスを初期化し、ビューオブジェクトを既知の状 態に設定します。ビューのインスタンスをコード内でプログラムによって作成する場合は、このメ ソッドを使用します。

7
7
0

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