前提・実現したいこと
TableViewのセルの削除をしたいです。
削除自体の実装はしたのですが、ページ遷移をすると削除したセルも再び出てきてしまいます。
調べてみたところ削除する際にuserdefaultsから該当する値をremoveすることは分かったのですが、
どうやって削除したら良いのか分からず困っています…
また、同じ配列の値を次の画面に渡したいとも思っています。。
ソースコード
Swift
1import UIKit 2 3class recipeViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { 4 5 @IBOutlet var tableview: UITableView! 6 7 var textArray:[String] = [] 8 9 override func viewDidLoad() { 10 super.viewDidLoad() 11 12 tableview.delegate = self 13 tableview.dataSource = self 14 15 } 16 //別のviewの"alertで保存したものを呼ぶ" 17 override func viewWillAppear(_ animated: Bool) { 18 textArray = UserDefaults.standard.array(forKey: "alert") as? [String] ?? [] 19 tableview.reloadData() 20 } 21 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 22 return textArray.count 23 } 24 25 //Cellのテキストに保存した"alert"を表示させる 26 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 27 let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") 28 29 cell.textLabel?.text = textArray[indexPath.row] 30 31 return cell 32 } 33 34 //Cellの削除(何故か復活する) 35 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { 36 if editingStyle == .delete { 37 textArray.remove(at: indexPath.row) 38 tableView.deleteRows(at: [indexPath], with: .fade) 39 } 40 } 41 //次の画面に値を渡しながら遷移したい 42 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 43 44 performSegue(withIdentifier: "detail", sender: nil) 45 } 46 47 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 48 49 let nextVC = segue.destination as! CopyViewController 50 if segue.identifier == "detail"{ 51 52 nextVC.recipe = textArray[indexPath.row] 53//Use of unresolved identifier 'indexPath'が出てエラーになる 54 55 } 56 } 57} 58
ツールのバージョン
Xcode : Version 11.0
Swift : Apple Swift version 5.1
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/10/03 06:06 編集
2019/10/03 06:21
2019/10/03 06:44