cell一行ずつにボタンを置き、ボタンが押されたらその行に表示されている画像とラベルのテキストを共有する…というものを作りたいのですが、ボタンが押された時、どの行のボタンか取得する方法はありませんでしょうか?
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
![guest](/img/icon/icnUserSample.jpg)
回答2件
0
UITableViewのアウトレットが必要です。
swift
1@IBOutlet weak var table: UITableView!
Swift3で書いたつもりですが、エラーが出たら適当に修正して下さい。
真面目に取得
swift
1@IBAction func pushedButton(sender: UIButton) { 2 //UITableView内の座標に変換 3 let point = table.convert(sender.center, from: sender) 4 //座標からindexPathを取得 5 if let indexPath = table.indexPathForRow(at: point) { 6 print(indexPath) 7 } else { 8 //ここには来ないはず 9 print("not found...") 10 }
せっかちな人向け
cell
-contentView
-UIButton
となっていることが条件です。
UIButtonの階層がもっと深い場合はsuperviewを増やして下さい。
swift
1@IBAction func pushedButton(sender: UIButton) { 2 if let indexPath = table.indexPath(for: sender.superview!.superview as! UITableViewCell) { 3 print(indexPath) 4 } else { 5 //ここには来ないはず 6 print("not found...") 7 } 8}
投稿2016/12/12 01:21
総合スコア16733
0
ベストアンサー
とりあえず思いついた2種類の方法を載せますので参考にしてみてください。
★ セルにIndexPath
のプロパティを作成する
swift
1// セル作成 2func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 3 let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath as IndexPath) as! CustomCell 4 cell.indexPath = indexPath 5 return cell 6} 7 8// カスタムセルクラス 9class CustomCell: UITableViewCell { 10 var indexPath = IndexPath() 11 12 @IBAction func pushCellButton(_ sender: UIButton) { 13 print(indexPath.row) 14 } 15}
★ セルボタンのtag
にindexPath.row
を設定する
swift
1// セル作成 2func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 3 let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath as IndexPath) as! CustomCell 4 cell.button.tag = indexPath.row 5 return cell 6} 7 8// カスタムセルクラス 9class CustomCell: UITableViewCell { 10 11 @IBOutlet weak var button: UIButton! 12 13 @IBAction func pushCellButton(_ sender: UIButton) { 14 print(sender.tag) 15 } 16}
投稿2016/12/11 01:06
編集2016/12/11 01:36総合スコア8490
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。