※この記事はCustomCellに置いたButtonの選択状態によってTableViewの処理を変える - Qiitaの記事をエクスポートしたものです。内容が古くなっている可能性があります。
開発環境
- Xcode 11.3
- Swift 5.0
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") } }