はじめに
TableViewCellが複数だと、どのCellのどのボタンが押されたのか判断が付かない
→CellのIndexPathが取得できれば可能
tableviewcell.swift
// セルに値をセットする
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// tableCell の ID で UITableViewCell のインスタンスを生成
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
// ボタンにタグを設定し、どのセルのボタンか判断する
let button = cell.viewWithTag(1) as! UIButton
button.addTarget(self, action: #selector(buttonPush(_:)), for: .touchUpInside)
button.tag = indexPath.row //タグを設定
print(indexPath.section) //分けない限り0固定
return cell
}
buttonPush.swift
@IBAction func buttonPush(_ sender: UIButton) {
//Int型からIndexPath型にキャスト
let indexPath = IndexPath(row: sender.tag, section: 0)
//indexPathでセルを指定可能
let cell = self.checkSheetTableView.cellForRow(at: indexPath)
// 作成したセルのタグ(4)のviewから値を取り出す
let countView = cell?.viewWithTag(4) as! CountView
print(countView.count) //Cell内のcountの値取得
}