質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

2回答

10942閲覧

UITableViewCellの中のボタンの処理

Kyoya1123

総合スコア54

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

3クリップ

投稿2016/12/11 00:53

cell一行ずつにボタンを置き、ボタンが押されたらその行に表示されている画像とラベルのテキストを共有する…というものを作りたいのですが、ボタンが押された時、どの行のボタンか取得する方法はありませんでしょうか?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答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

fuzzball

総合スコア16731

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

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}

★ セルボタンのtagindexPath.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
_Kentarou

総合スコア8490

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問