簡単なTodoアプリを作りました。
上記の画像の通り、ただタスクを追加するだけなので、タスクがどんどん溜まっていくので、削除したくなりました。
そこで、ネット上にこのような記事を見つけまして、
(引用:https://qiita.com/mironal/items/bb0ab5c42fe687b301ec)
記事の中で、
// delete を押したところの場所 let index = indexPath.row items.removeAtIndex(index) tableView.reloadData()
で削除できると書かれてありました。
早速Todoアプリのコードに加えましたが、下記のエラーが発生しました。
cell_array.removeAtIndex(index) ← Value of type '[String]' has no member 'removeAtIndex'
恐らく、タスクを保存する配列の型であるStringはremoveAtIndexを持ってない、と言っているのでしょう。
しかし、配列の方を[String]型にしても、AddControllerにある、
cell_array.append(textField.text!)
の箇所で
Cannot convert value of type 'String' to expected argument type 'inout Array<_>'
というエラーが発生してしまいます。
僕としては、Mac標準アプリのリマインダーアプリのように、スワイプでタスクを削除できるようにしたいです。
どうか、解決方法を提示しただきたいです。
よろしくお願いします。
以下がソースコードです。
ViewController
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.removeAtIndex(index) //ここでエラーが発生しました 23 tableView.reloadData() 24 } 25 26 override func viewDidLoad() { 27 super.viewDidLoad() 28 // Do any additional setup after loading the view, typically from a nib. 29 //UDに保存された中身を受け取る 30 if UserDefaults.standard.object(forKey: "TodoList") != nil { 31 cell_array = UserDefaults.standard.object(forKey: "TodoList") as! [String] 32 } 33 } 34 35 override func didReceiveMemoryWarning() { 36 super.didReceiveMemoryWarning() 37 // Dispose of any resources that can be recreated. 38 } 39 40} 41
AddController
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
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/30 03:16