以前、下記の質問をしました。
↓
「【Swift,Xcode】Todoアプリのタスクをスワイプで削除したい」
https://teratail.com/questions/143780
上記の質問のおかげで、タスクをスワイプで削除できました。
しかし、タスクを削除し、Todoアプリを再起動すると、削除されていない状態に戻っていました。
例えると、”アプリ”というタスクを削除し、1度アプリのウィンドウを消し、再びアプリを起動すると、”アプリ”のタスクが残っていました。
僕としては、1度削除されたら、次起動した時には無い状態にしたいです。
どうかご回答よろしくお願いします。
ViewController
1import UIKit 2 3//変数を格納する配列 4var cell_array = [String]() 5 6class AddController: UIViewController { 7 8 override func viewDidLoad() { 9 super.viewDidLoad() 10 11 // Do any additional setup after loading the view. 12 } 13 14 override func didReceiveMemoryWarning() { 15 super.didReceiveMemoryWarning() 16 // Dispose of any resources that can be recreated. 17 } 18 19 20 @IBOutlet weak var textField: UITextField! 21 22 @IBAction func addButton(_ sender: Any) { 23 //入力したテキストを追加する 24 cell_array.append(textField.text!) 25 //textFieldの値を削除する 26 textField.text = "" 27 //UDに登録する 28 UserDefaults.standard.set(cell_array, forKey: "TodoList") 29 } 30 31 32}
AddController
1import UIKit 2 3class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 4 5 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 6 //セルの数を返す 7 return cell_array.count 8 } 9 10 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 11 //セル用の変数を作る 12 let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath) 13 //UDに登録されたセルの中身を格納する 14 cell.textLabel!.text = cell_array[indexPath.row] 15 //表示するセルを返す 16 return cell 17 } 18 19 //タスクを削除する 20 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 21 let index = indexPath.row 22 cell_array.remove(at:index) 23 UserDefaults.standard.synchronize() 24 tableView.reloadData() 25 } 26 27 override func viewDidLoad() { 28 super.viewDidLoad() 29 // Do any additional setup after loading the view, typically from a nib. 30 //UDに保存された中身を受け取る 31 if UserDefaults.standard.object(forKey: "TodoList") != nil { 32 cell_array = UserDefaults.standard.object(forKey: "TodoList") as! [String] 33 } 34 } 35 36 override func didReceiveMemoryWarning() { 37 super.didReceiveMemoryWarning() 38 // Dispose of any resources that can be recreated. 39 } 40 41 42 43 44} 45 46
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/30 05:17