swiftでcheckboxやradiobuttonを実装するライブラリ

はじめに

swift(objective-c)でのiosアプリ開発していて、標準のuikitにはhtmlでのチェックボックスラジオボタンなどに相当する部品がありませんでした。で、まぁ探していたらCTCheckboxというちょうどいい感じのライブラリがあったので使い方メモしておきます

完成イメージ

f:id:yoppy0066:20150603022907p:plain

こんなかんじでテーブルビューに追加してみました。ありがちなuiですね。
また、選択中のセルを配列に保持してボタンなどを押した際に選択値を送信できるようにしてみたいと思います

ちなみにCTCheckboxオリジナルだとチェックボックスが四角いの形です。今回は丸形のラジオボタン風にしました。
また、CTCheckboxは以下からダウンロードできます。
https://github.com/rizumita/CTCheckbox

CTCheckboxはObjective-cで書かれているためswiftから使う場合は、***-Bridging-Header.hファイルの追加も必要になります。
これは検索すればたくさん情報があるので大丈夫かと思います

実装(CTCheckboxの準備)

***-Bridging-Header.h

#import "CTCheckbox.h"

CTCheckbox.mの174行目らへん

変更前

    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(CGRectGetMinX(frame) + floor(CGRectGetWidth(frame) * 0.05000 + 0.5), CGRectGetMinY(frame) + floor(CGRectGetHeight(frame) * 0.05000 + 0.5), floor(CGRectGetWidth(frame) * 0.95000 + 0.5) - floor(CGRectGetWidth(frame) * 0.05000 + 0.5), floor(CGRectGetHeight(frame) * 0.95000 + 0.5) - floor(CGRectGetHeight(frame) * 0.05000 + 0.5)) cornerRadius:4];

変更後

    UIBezierPath *roundedRectanglePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(CGRectGetMinX(frame) + floor(CGRectGetWidth(frame) * 0.05000 + 0.5), CGRectGetMinY(frame) + floor(CGRectGetHeight(frame) * 0.05000 + 0.5), floor(CGRectGetWidth(frame) * 0.95000 + 0.5) - floor(CGRectGetWidth(frame) * 0.05000 + 0.5), floor(CGRectGetHeight(frame) * 0.95000 + 0.5) - floor(CGRectGetHeight(frame) * 0.05000 + 0.5)) cornerRadius:10];

1番後ろの、cornerRadius:4の箇所をcornerRadius:10に変更して、丸型のラジオボタン風に変更しました。

実装(CTCheckboxを使用)

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    // テーブルビュー
    var tableView: UITableView!
    
    // テーブルデータ
    var tableData = [
        "データ1",
        "データ2",
        "データ3",
        "データ4",
        "データ5",
    ]
    
    // 選択中のセル
    var selected = [
        false,
        false,
        false,
        false,
        false,
    ]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let barHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
        
        let displayWidth = self.view.frame.width
        let displayHeight = self.view.frame.height
        
        tableView = UITableView(frame: CGRect(x:0, y:barHeight, width:displayWidth, height:displayHeight - barHeight))
        
        tableView.registerClass(CustomTableViewCell.self, forCellReuseIdentifier: "CustomTableViewCell")
        
        tableView.delegate = self
        tableView.dataSource = self
        
        self.view.addSubview(tableView)
    }

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

    // tableviewのデリゲートメソッドの一部省略・・・
    
    // テーブルセルにデータをセットします
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as! CustomTableViewCell
        cell.textLabel?.text = tableData[indexPath.row]
        
        cell.checkbox.tag = indexPath.row
        cell.checkbox.addTarget(self, action: "checked:", forControlEvents: .ValueChanged)
        cell.setData()
        return cell
    }
    
    // ⭐️ここがポイント セルの選択状態を保持します
    func checked(sender:CTCheckbox) {
        selected[sender.tag] = sender.checked
    }
}

class CustomTableViewCell: UITableViewCell
{
    var checkbox = CTCheckbox()

    func setData() -> Void {
        // ⭐️ここもポイント チェックボックスを追加します
        checkbox.frame = CGRectMake(self.frame.width - 44, 0, 22, self.frame.height)
        checkbox.checkboxColor = UIColor.blackColor()
        checkbox.checkboxSideLength = 22
        self.addSubview(checkbox)
    }
}

ソースそのままになりますが、上記のような形にしてみました。
チェック状態の変更のタイミングでselectedにも反映させるので、ボタンなどを押した際にこの値を参照すれば選択値を送信したりとかできそうです

おわりに

勉強し始めて3ヶ月位経ちましたが、htmlだと簡単にできるのにiosプログラムだと簡単にできなくて戸惑うことがまだまだ多いです。
まぁ1 つずつこなしてゆくしかないのですが、、、

以上です