LoginSignup
9
6

More than 3 years have passed since last update.

TableViewCell のIndexPathと値抽出

Last updated at Posted at 2019-09-03

はじめに

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の値取得
      }

9
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
6