上記の方法を質問させてください。
現在、TableViewを用いたプログラムを作っています。
UITableViewで作成しており、cellをタップしたことをきっかけに、
その後のActionを実行させるプログラムを書いています。
cell自体をタップした時にはきちんとコードは通るのですが、
それ以外、例えば、NavigationBarButtonから
didselectRowの中身のコードを走らせたい場合などは
どのようにコードすればいいのでしょうか?
self.tableView.selectRow(at: [0, 1], animated: true, scrollPosition: .none)
を用いて、cellを選択するコードを通しても、highlightされるだけで、
didSelectRowAtの中身まで走らず、困っております。
解決策は強引な方法では浮かびますが、
(didSelectRowAtの中身を別functionにして、それを両方で呼び出す)
self.tableView.selectRowを指定するだけもしくは、簡単な方法で、
didSelectRowAtをtriggerする方法はないのでしょうか?
簡易化したコードを下に載せさせてもらいました。
下記のコードでは
@IBActionのボタンをtapしても、didSelectRowAtの
actionBのprint("actionB")が表示されなくて困ってます。
ちなみに、本当のプログラムは、
customCellにtextFieldを配置してて、
いきなり2行目のcellをtapした場合、1行目のtextFieldが空白の場合、
Alertを表示し、1行目に戻りますか?で「はい」を選んだら、
1行目のtextFieldをfirstResponderに起動したいというコードです。
1行目を最初に選んだ場合はもちろん問題なく動いてます。
Swift
1 2import UIKit 3 4class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 5 6 @IBOutlet weak var tableView: UITableView! 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 // Do any additional setup after loading the view, typically from a nib. 11 } 12 13 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 14 return 2 15 } 16 17 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 18 let cell = tableView.dequeueReusableCell(withIdentifier: "sampleCell") 19 cell?.textLabel?.text = String(indexPath.row) 20 21 return cell! 22 } 23 24 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 25 print("selected row", indexPath.row) 26 switch indexPath.row { 27 case 0: 28 self.actionA() 29 break 30 case 1: 31 self.actionB() 32 break 33 default : 34 print("selected default") 35 break 36 } 37 } 38 39 func actionA() { 40 print("actionA") 41 } 42 43 func actionB() { 44 print("actionB") 45 } 46 47 @IBAction func btnPressed(_ sender: UIBarButtonItem) { 48 print("Select Btn pressed.") 49 self.tableView.selectRow(at: [0, 1], animated: true, scrollPosition: .none) 50 // ↑上記でactionBがトリガーされない 51 } 52 53} 54 55
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/09 04:22
2019/01/09 04:50
2019/01/09 05:49