32
33

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

どうやってswiftでチェックボックス実装するの? #swift

Posted at

Version

Xcode: Version 9.2

事前準備

check boxのオンとオフのボタンを用意して、Assetsの中に入れておく

png.png

UIButtonを拡張したチェックボックスのボタンクラスを作成する

  • CheckBox.swift

import UIKit

class CheckBox: UIButton {
    // Images
    let checkedImage = UIImage(named: "ico_check_on")! as UIImage
    let uncheckedImage = UIImage(named: "ico_check_off")! as UIImage
    
    // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, for: UIControlState.normal)
            } else {
                self.setImage(uncheckedImage, for: UIControlState.normal)
            }
        }
    }
    
    override func awakeFromNib() {
        self.addTarget(self, action:#selector(buttonClicked(sender:)), for: UIControlEvents.touchUpInside)
        self.isChecked = false
    }
    
    func buttonClicked(sender: UIButton) {
        if sender == self {
            isChecked = !isChecked
        }
    }
}

ボタンを配置

ストーリーボードにボタンを配置しておく

配置したボタンにカスタムクラスを設定する

Main.storyboard.png

チェックボックスのオンとオフ

ボタンからアクションを作成して、_ sender: CheckBoxにして、プロパティを参照

    @IBAction func checkView(_ sender: CheckBox) {

        print(sender.isChecked)

    }

参考

xcode - How to create radio buttons and checkbox in swift (iOS)? - Stack Overflow

32
33
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?