編集モード・通常モードの切替
editButtonItemメソッドで編集モード・通常モードの切り替えボタンを取得できます。
このボタンは押す度にEdit → Doneが切り替わると同時にTableViewのモードも切り替わります。
class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = editButtonItem() } }
UIViewControllerにUITableViewを設置する場合はsetEditingをオーバーライドする必要があります。
override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) }
削除可能かの判定
canEditRowAtIndexPathメソッドでどのテーブルが削除可能かを制御できます。
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return indexPath.row == 1 }
削除ボタンを押すとcommitEditingStyleメソッドが呼ばれるのでその中に削除処理を記述します。
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { }
編集中のaccessoryType
編集中のaccessoryTypeはStoryboardのEdditing Accessoryで設定します。
削除ボタンのテキスト
削除ボタンのテキストはtitleForDeleteConfirmationButtonForRowAtIndexPathメソッドをオーバーライドする事で変更できます。
override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return "非表示" }
並び替え
並び替え可能する為にはmoveRowAtIndexPathメソッドを実装します。
このメソッドは並び替えが終わったタイミングで呼ばれるメソッドです。
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { }
並び替え可能かを制御するにはcanMoveRowAtIndexPathメソッドを使います。
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true }