たろすの技術メモ

Jot Down the Tech

ソフトウェアエンジニアのメモ書き

CustomCellに置いたButtonの選択状態によってTableViewの処理を変える

※この記事はCustomCellに置いたButtonの選択状態によってTableViewの処理を変える - Qiitaの記事をエクスポートしたものです。内容が古くなっている可能性があります。

開発環境

UIButtonのextensionを作る

// CustomCell.swift
extension FaveButton {
    func switchAction(onAction: @escaping ()->Void, offAction: @escaping ()->Void) {
        switch self.isSelected {
        case true:
            //ONにする時に走らせたい処理
            onAction()
        case false:
            //OFFにする時に走らせたい処理
            offAction()
        }
    }
}

ButtonActionにDelegateを設定する

// CustomCell.swift
import UIKit

protocol CellDelegate: AnyObject {
    func didTapButton(cell: CustomCell) //ON
    func didUnTapButton(cell: CustomCell) //OFF
}
class CustomCell: UITableViewCell {
    weak var delegate: CellDelegate?

@IBAction func didButtonTapped(_ sender: UIButton) {
        sender.switchAction(onAction: {
//TableViewController.swiftのdidTapButton()に委任
            self.delegate?.didTapButton(cell: self)
        },offAction: {
//TableViewController.swiftのdidUnTapButton()に委任
            self.delegate?.didUnTapButton(cell: self)
        })
    }
}
// TableViewController.swift
import UIKit

class TableViewController: UITableViewController, CellDelegate /*追記*/ {

func didTapButton(cell: CustomCell) {
     print("ON")
    }

func didUnTapButton(cell: CustomCell) {
        print("OFF")
    }
}

参考

【iOS】UIButtonにON/OFFのスイッチ処理を1行で書く【Swift】