【Swift】CollectionViewのカスタムセルをタップすることでUISwitchを切り替える


どういうことか

こういうことがやりたい。

どうするのか

  • xibを使ってUIを作るが、この際にUIButtonでセル全体を覆ってしまうのがコツ
  • どちらのセルをタップしたのかの判定も入れる
  • Delegateを使う

カスタムセル側

ToggleCollectionViewCell.swift
protocol ToggleCollectionViewCellDelegate {
    func toggleSwitchAction(toggleSwitchCheck: Bool, type: String)
}

class ToggleCollectionViewCell: UICollectionViewCell, Reusable {

    @IBOutlet weak var toggleSwitch: UISwitch!

    var toggleSwitchCheck = false

    // どっちのセルをタップしたのか判定するための変数
    var contentType = ""

    var delegate: ToggleCollectionViewCellDelegate?

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    @IBAction func titleButtonAction(_ sender: Any) {

        // スイッチの切替処理
        if toggleSwitchCheck {
            toggleSwitch.setOn(false, animated:true)
            toggleSwitchCheck = false
        } else {
            toggleSwitch.setOn(true, animated:true)
            toggleSwitchCheck = true
        }

        // スイッチの判定とセルの判定を渡してあげる
        delegate?.toggleSwitchAction(toggleSwitchCheck: toggleSwitchCheck,  type: contentType)
    }
}

Controller側

Delegateメソッドはextensionに書きます(自由ですが)。
セルをタップすることでController内のメンバ変数が切り替わるので、それによってなんらかの処理をしてあげるといい感じです。

ViewController.swift

    // メンバ変数
    var areYaru = false
    var koreYaru = false

// 中略

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = CollectionViewUtility.createCell(collectionView, identifier: ToggleCollectionViewCell.reusableIdentifier, indexPath) as! ToggleCollectionViewCell

        switch (indexPath.section) {

        case 0:
            cell.titleButtonLabel.setTitle("あれをやる", for: .normal)
            cell.delegate = self
            cell.contentType = "are"

            return cell

        case 1:
            cell.titleButtonLabel.setTitle("これをやる", for: .normal)            
            cell.delegate = self
            cell.contentType = "kore"

            return cell

        default:
            return UICollectionViewCell()
        }
    }

// 中略

extension ViewController: ToggleCollectionViewCellDelegate {

    // Delegateメソッド
    func toggleSwitchAction(toggleSwitchCheck: Bool, type: String) {

        if type == "userId" {
            areYaru = toggleSwitchCheck
        } else if type == "biometrics" {
            koreYaru = toggleSwitchCheck
        } else {
            print("error")
        }
    }
}

おわり(´・ω・`)