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 override func didReceiveMemoryWarning() { 26 super.didReceiveMemoryWarning() 27 // Dispose of any resources that can be recreated. 28 } 29 30 31}
このようにデバッグすると「cell 追加」というcellを出すことまでは出来たのすがこのcellをタップした時にアラートテキストを起動させて入力した値をcellに反映させたいです。
他の方の質問を見たところこのようなコードでアラートで入力した内容が反映されるのはわかったのですがこれをどう組み込めばいいのか分からなく困っています。
@IBAction func addName(_ sender: Any) { let alert = UIAlertController(title: "New name", message: "Enter a new name", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { (action) in let textField = alert.textFields?.first self.saveName(name: textField!.text!) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alert.addTextField(configurationHandler: nil) alert.addAction(saveAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } func saveName(name: String){ let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let person = Person(entity: Person.entity(), insertInto: context) person.setValue(name, forKey: "name") do{ try context.save() people.append(person) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext do{ let result = try context.fetch(Person.fetchRequest()) people = result as! [Person] }catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。