質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

1263閲覧

[swift 5]cellのチェックマークを維持したい

Kaguya_4869

総合スコア116

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2019/11/19 13:02

#質問したいこと
現在、Todoリストアプリのようなものを作っています。そこで、アプリが終了した後にもチェックマークが維持されるようにしたいです。
#コード

swift5

1import UIKit 2 3//変数の設置 4var todo = [String]() 5 6class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { 7 8 9 @IBOutlet weak var maintextField: UITextField! 10 @IBOutlet weak var tableView: UITableView! 11 12 13 //追加ボタン 14 @IBAction func TodoAddButton(_ sender: Any) { 15 //変数に入力内容を入れる 16 todo.append(maintextField.text!) 17 //追加ボタンを押す→フィールドを空にする 18 maintextField.text = "" 19 // 20 21 //変数の中身をUDに追加 22 UserDefaults.standard.set(todo, forKey: "TodoList") 23 24 print("書き込み成功") 25 26 maintextField.resignFirstResponder() 27 28 29 } 30 31 32 33 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 34 if let cell = tableView.cellForRow(at: indexPath) { 35 cell.accessoryType = .checkmark 36 } 37 } 38 func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { 39 if let cell = tableView.cellForRow(at: indexPath) { 40 cell.accessoryType = .none 41 } 42 43 } 44 45 46 //textFieldキーボードしまう 47 func textFieldShouldReturn(_ textField: UITextField) -> Bool { 48 maintextField.resignFirstResponder() 49 return true 50 } 51 52 53 //UITableView,numberOfRowsInSectionの追加(表示するcellの数を決める) 54 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 55 56 57 //表示するcell数 58 return todo.count 59 } 60 //UITableView、cellForRowAtの追加(表示するcellの中身を決める) 61 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 62 //変数を作る 63 let todocell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath) 64 //変数の中身を作る 65 todocell.textLabel!.text = todo[indexPath.row] 66 // セルの状態を確認しチェック状態を反映する 67 let selectedIndexPaths = tableView.indexPathsForSelectedRows 68 if selectedIndexPaths != nil && (selectedIndexPaths?.contains(indexPath))! { 69 todocell.accessoryType = .checkmark 70 } else { 71 todocell.accessoryType = .none 72 } 73 74 //表示する中身 75 return todocell 76 } 77 78 //セルの編集許可 79 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool 80 { 81 return true 82 } 83 84 //スワイプしたセルを削除 85 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { 86 if editingStyle == UITableViewCell.EditingStyle.delete { 87 88 //itemArray.remove(at: indexPath.row) 89 todo.remove(at: indexPath.row) 90 91 // todoが更新されたので保存 92 UserDefaults.standard.set(todo, forKey: "TodoList" ) 93 94 95 tableView.deleteRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic) 96 } 97 98 99 100 } 101 102 103 override func viewDidLoad() { 104 super.viewDidLoad() 105 106 self.maintextField.delegate = self 107 tableView.allowsMultipleSelection = true 108 109 110 111// //追加画面で入力した内容を取得する 112// if UserDefaults.standard.object(forKey: "TodoList") != nil { 113// todo = UserDefaults.standard.object(forKey: "TodoList") as! [String] 114// } 115 116 //追加画面で入力した内容を取得する 117 if let todos = UserDefaults.standard.object(forKey: "TodoList") as? [String] { 118 todo = todos 119 } 120 121 // Do any additional setup after loading the view. 122 } 123 124 125 /* 126 // MARK: - Navigation 127 128 // In a storyboard-based application, you will often want to do a little preparation before navigation 129 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 130 // Get the new view controller using segue.destination. 131 // Pass the selected object to the new view controller. 132 } 133 */ 134 135} 136

#やってみたこと
色々調べてみたのですが、自分の未熟な知識ですとよく理解ができず、質問させていただいた次第です。
ぜひ、丁寧に教えてくださると助かります。(自分勝手で申し訳ありません。)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

todoの保存と読み出しができているので、同じようにやってみるのはどうでしょうか。チェックマークの状態をテーブルの選択状態で表現しているので、

  • tableView.indexPathsForSelectedRowsで選択しているセルのIndexPathの一覧がとれるので、その情報を元にIntの配列等を作って、UserDefaultsに保存しておく。

  • viewDidLoadで読み出して、tableView.selectRow(at:animated:scrollPosition:)を使ってテーブルビューの選択状態を復元する。

という感じにすればよいと思います。

TableViewの選択状態を使うのも手ですが、配列などに自分でチェックの状態を保持しておくという方法でも良いと思います。

投稿2019/11/19 15:16

eytyet

総合スコア803

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Kaguya_4869

2019/11/20 03:53

できました! ありがとうございます!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問