実現させたいこと
add cellをタップした時にアラートテキストが呼び出されてそこで入力した内容をadd cellの上のtableviewに表示出来るようにしたいです。
swift
1import UIKit 2 3class ViewController: UIViewController,UITabBarDelegate,UITableViewDataSource { 4 5 @IBOutlet weak var mytableView: UITableView! 6 7 var kei = ["cell 追加"] 8 9 10 override func viewDidLoad() { 11 super.viewDidLoad() 12 // Do any additional setup after loading the view, typically from a nib. 13 } 14 15 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 16 return 1 17 } 18 19 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 20 let cell = UITableViewCell(); 21 cell.textLabel?.text = kei[indexPath.row] 22 return cell 23 } 24 25 func tableView(_ tableView: UITableView, didSelectRowAtIndexPath: IndexPath) -> UITableViewCell { 26 27 let alert = UIAlertController(title: "タイトル", message: "メッセージ", preferredStyle: .alert) 28 29 // OKボタンの設定 30 let okAction = UIAlertAction(title: "OK", style: .default, handler: { 31 (action:UIAlertAction!) -> Void in 32 33 // OKを押した時入力されていたテキストを表示 34 if let textFields = alert.textFields { 35 36 // アラートに含まれるすべてのテキストフィールドを調べる 37 for textField in textFields { 38 print(textField.text!) 39 } 40 } 41 }) 42 alert.addAction(okAction) 43 44 // キャンセルボタンの設定 45 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) 46 alert.addAction(cancelAction) 47 48 // テキストフィールドを追加 49 alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in 50 textField.placeholder = "テキスト" 51 }) 52 53 54 alert.view.setNeedsLayout() // シミュレータの種類によっては、これがないと警告が発生 55 56 // アラートを画面に表示 57 self.present(alert, animated: true, completion: nil) 58 return cell 59 } 60 61 62 override func didReceiveMemoryWarning() { 63 super.didReceiveMemoryWarning() 64 // Dispose of any resources that can be recreated. 65 } 66 67 68 69}
tableView外にボタンを設置してそこからアラートテキストを呼び出して入力した内容をtableViewに反映させることはできるのですがtableView内のテキストをタップしてデータを反映させることがどうしても分からないので教えていただきたいです。
swift
1func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 2 return kei.count 3 }
swift
1for textField in textFields { 2 self.kei.append(textField.text!) 3 } 4 self.mytableView.reloadData()
以下の部分を訂正したことによってcell追加をタップして入力させることができるようになったのですが理想としてはcell追加の上に入力した内容が反映されるようにしたいです。
イメージとしてはこのようにしたいです。
回答2件
あなたの回答
tips
プレビュー