LoginSignup
5
5

More than 5 years have passed since last update.

UIButtonのサブクラス Swift

Last updated at Posted at 2015-12-20

UIButtonをSuperClassにもつSubClassが欲しくて作ってみました。

imageを2つ用意していてタップすれば画像が変わるUIButtonのSubClassです。

storyboardでUIButtonを配置する場合のsubclassの作り方はたくさん載っていたのですが、storybordは使わないコードーのみの方法がなかったのでメモ代わりに、、、(10行ほど付け足すだけですけど)

SampleButton.swift
import UIKit

class SampleButton: UIButton {

    let onImage = UIImage(named: "image")
    let offImage = UIImage(named: "image2")

    var isTapped: Bool = false {
        didSet {
            if isTapped {
                self.setImage(onImage, forState: .Normal)
            } else {
                self.setImage(offImage, forState: .Normal)
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isTapped = false
        self.setImage(offImage, forState: .Normal)
        self.addTarget(self, action: "tapButton:", forControlEvents: UIControlEvents.TouchUpInside)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func awakeFromNib() {
        self.addTarget(self,action:"tapButton:", forControlEvents: UIControlEvents.TouchUpInside)
        self.isTaped = false
    }

    func tapButton(sender: UIButton) {
        if sender == self {
            isTapped = !isTapped
        }
    }
}

storybordを使わずにsubclassを作る際に大切なのはココです。

swift1.2から required initも必要になったようです。


override init(frame: CGRect) {
    super.init(frame: frame)
    self.isTapped = false
    self.setImage(offImage, forState: .Normal)
    self.addTarget(self, action: "tapButton:", forControlEvents: UIControlEvents.TouchUpInside)
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

逆にこの初期化するメソッドをコメントアウトすれば、UIButtonのCustomClassとして StoryBord で使用できます。

スクリーンショット 2015-12-20 15.04.51.png

Swift version 2.1.1

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