Swiftで遊ぼう! - 626 - CoreDataDemo3 - 8 TableViewCellの削除や編集の扱い
- Swiftで遊ぼう!の前書き-> Life-LOG OtherSide
- Swift2.1 & Xcode7.1対応の日本語版アップルチュートリアル!
- Table View実装チュートリアルをXcode7.2.1で解説
- Core Data シンプルチュートリアル
- 私の本業、オフィシャルなブログ-> Life-LOG
今までのところでデーターベースの項目を加えるコーディングができました。
次はTable Viewの標準的な機能、Cellをスワイプすることで消去ボタンを出現させ、そのボタンを使って永続保存されたデータを消去するステップです。
実はTableViewCellの編集や削除ボタンの扱いを今まで扱ったことが無かったので、今日は少し調べてまとめました。TableViewに標準で備わっている機能なのでメソッドを実装するだけなんですが、このメソッドの取り扱いで分からないところが多いんです(T_T)
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true }
プロトコールで用意されているオプショナルメソッドです。まずCellを編集可能な状態にしなければならないため次のメソッドで「true」を返す必要があるという説明がありました。しかし、このコードがあっても無くても編集はできるんです。必要ないような...???
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let item = students[indexPath.row] students.removeAtIndex(indexPath.row) let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = delegate.managedObjectContext context.deleteObject(item) try! context.save() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } }
このメソッドはチュートリアルで使用されていたメソッドです。実はこのメソッドで表示できるのは「delete」ボタンだけなんです。Cellをスワイプすると次のようなボタンが出現します。
よくありがちな「edit」ボタンが無いんです。このメソッドをどのように拡張したら「edit」ボタンを加えることができるのかネットで調べていると次のようなメソッドの実装を見つけました。
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let editAction = UITableViewRowAction(style: .Normal, title: "edit"){(action, indexPath) in print("\(indexPath) was edited") } editAction.backgroundColor = UIColor.greenColor() let deleteAction = UITableViewRowAction(style: .Default, title: "delete"){(action, indexPath) in let item = self.students[indexPath.row] self.students.removeAtIndex(indexPath.row) let delegate = UIApplication.sharedApplication().delegate as! AppDelegate let context = delegate.managedObjectContext context.deleteObject(item) try! context.save() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) } deleteAction.backgroundColor = UIColor.redColor() return [editAction, deleteAction] }
「edit」ボタンに実装はしていません。「delete」ボタンを押すとデータは消去されるので、上記のコードと同様です。同じコードをクロージャーとして与えているので、自分の持っているプロパティにアクセスするために「self.」を付ける必要があります。
TableViewCellの編集コードを自分なりに作り変えてみてもいいのですが、NSFetchResultsControllerの実装の勉強をしたいので次に進みます。
今日はここまで。