前提として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。