LoginSignup
5
3

More than 5 years have passed since last update.

SwiftでUIButtonTypeが.customのサブクラスを作る

Last updated at Posted at 2016-07-19

UIButtonをカスタマイズする際に、UIButtonのサブクラスを作ると思います。

そのクラスをボタンに適用する方法として、Storyboardの場合はXcodeの Custom Class にクラス名を設定し、併せてButtonのTypeを Custom に設定します。これを忘れるとボタンが意図した挙動にならなかったりします。

xcode.png

そこで、サブクラス内にコードでButtonTypeを設定できれば良いのでは?
と思い調べてみました。


Objective-C時代には、init内で

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame: frame];
    if (self) {
        self = [UIButtonbuttonWithType: UIButtonTypeCustom];
    }
    return self;
}

みたいなこともできたようです。(動作未検証)


ですが、Swift場合は、 self への代入はできませんでした。

self = UIButton(type: .custom)

// Cannot assign to value: 'self' is immutable

また、 buttonType というプロパティがあったのですが、

buttonType = .custom

// 'buttonType' is a get-only property

読み出し専用だと怒られてしまいます。


ここで、ひとつの疑問が浮かびました。

「コードだけで .custom なサブクラスはどうやってつくるのか?」

下記ページによると、Swiftでは UIButton のサブクラスは .custom がデフォルトとのことです。

http://stackoverflow.com/questions/27079681/how-to-init-a-uibutton-subclass


検証してみましょう。

let button = MyCustomButton()
print(button.buttonType.rawValue)

// 0

0が出力されました。

UIButtonTypeの定義部分をみるとcustom = 0 で正しいようです。

public enum UIButtonType : Int {
    case custom
    case system
    case detailDisclosure
    case infoLight
    case infoDark
    case contactAdd
}

この場合は、未設定なのでデフォルト値の custom になってると言った方が正しいでしょうか。

そして残念ながら、ButtonTypeをCustomに設定し忘れる問題をコード側で解決することはできないようです。


結論

  • コードの場合はデフォルトで.customの設定となる
  • Storyboardの場合は忘れずにButtonのTypeをCustomに設定する
5
3
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
5
3