8
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SwiftでUITableViewCellの中にUIButtonを置いてタッチイベントを取得

Last updated at Posted at 2018-07-29

前提としてButton自体は、カスタムのCellクラスの中にあります。
いくつかやり方はあると思いますが、今回は呼び出し元のViewControllerの方に記述をしています。

extension ViewController:UITableViewDataSource {
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       ... 省略

       cell.someButton.addTarget(self, action: "pushButton:", for: .touchUpInside)

       ... 省略
    }

    ... 省略

}

@objc private func pushButton(_ sender:UIButton)
{
        
}

privateってのを記述しないといけないってわかるまでSIGBRTしまくってました。手こずりました。

ただこのままだと、どのCellをタップしたかはわからないので、indexPath.rowを渡してあげます。UIButtonのカスタムクラスを作って渡す方法もありますが、行番号だけ渡せれば問題ないので、tagを使って渡すことにします。

こんな感じ。

       cell.someButton.tag = indexPath.row
       cell.someButton.addTarget(self, action: "pushButton:", for: .touchUpInside)

取り出す方は、

@objc private func pushButton(_ sender:UIButton)
{
    let row = sender.tag
    let data = self.jsonData[row]
}

あとは、Cellに表示させているデータから該当のデータを取得すればOK。

8
11
2

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
8
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?