LoginSignup
19
18

More than 5 years have passed since last update.

Swiftでチェックボックスを実装する(Swift2.1, XCode7.2)

Posted at

iOSにはチェックボックスがないですが、業務アプリを開発する上で必要になったのでメモしておきます。

画像用意

check.png

nocheck.png

プロジェクトに画像追加

作成した画像をドラッグしてプロジェクトに追加する。
スクリーンショット 2016-03-10 18.21.15.jpg

コーディング

import UIKit

class ViewController: UIViewController {
    var myButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myButton = UIButton()
        myButton.frame = CGRectMake(0,100,200,40)
        myButton.addTarget(self, action: "onClickMyButton:", forControlEvents: .TouchUpInside)
        // ボタンに画像セット
        myButton.setImage(UIImage(named: "check.png"), forState: UIControlState.Selected)
        myButton.setImage(UIImage(named: "nocheck.png"), forState: UIControlState.Normal)

        self.view.addSubview(myButton)
    }

    internal func onClickMyButton(sender: UIButton){
        myButton.selected = !myButton.selected
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

結果

スクリーンショット 2016-03-10 18.29.03.jpg

スクリーンショット 2016-03-10 18.29.10.jpg

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