9
9

More than 3 years have passed since last update.

UITableViewCellのボタンをどのCellのものか判別する

Posted at

自分へのリマインドを主として書いています。
分かりにくかったら申し訳ないです。

UITableViewCellにボタンを追加

  • addTargetを追加
sample.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell
       let button = UIButton()
       button.addTarget(self, action: #selector(self.buttonEvent(_: )), for: UIControl.Event.touchUpInside)

       return cell
}

- タップされたときのメソッド

sample.swift
 @objc func buttonEvent(_ sender: UIButton) {
        print("tapped.")
    }

tapされたボタンのCellを判定する

今回はbuttonにタグを設定する方法を紹介します。
- buttonにtagを追加
UIButtonにはInt型のtagをつけることができます、これをcellを追加する際にボタンに設定しておくことでボタンがどのセルのボタンなのかを判別できるようになります。

sample.swift
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell
       let button = UIButton()
       button.addTarget(self, action: #selector(self.buttonEvent(_: )), for: UIControl.Event.touchUpInside)
       //タグの設定
       cell.button.tag = indexPath.row

       return cell
}
  • メソッドの書き換え
sample.swift
 @objc func buttonEvent(_ sender: UIButton) {
        print("tapped: \([sender.tag])番目のcell"
 }

Reference

CustomCellのボタンをどのCellのものか判別する

9
9
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
9