しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

UITableViewの編集モードを実装する

編集モード・通常モードの切替

editButtonItemメソッドで編集モード・通常モードの切り替えボタンを取得できます。
このボタンは押す度にEdit → Doneが切り替わると同時にTableViewのモードも切り替わります。

class ViewController: UITableViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.rightBarButtonItem = editButtonItem()
    }
}

f:id:llcc:20160215211223p:plain

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
}

f:id:llcc:20160215212552p:plain

削除ボタンを押すとcommitEditingStyleメソッドが呼ばれるのでその中に削除処理を記述します。

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}

編集中のaccessoryType

編集中のaccessoryTypeはStoryboardのEdditing Accessoryで設定します。

f:id:llcc:20160215213148p:plain

削除ボタンのテキスト

削除ボタンのテキストはtitleForDeleteConfirmationButtonForRowAtIndexPathメソッドをオーバーライドする事で変更できます。

override func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
    return "非表示"
}

f:id:llcc:20160215213445p:plain

並び替え

並び替え可能する為にはmoveRowAtIndexPathメソッドを実装します。
このメソッドは並び替えが終わったタイミングで呼ばれるメソッドです。

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
}

f:id:llcc:20160215213823p:plain

並び替え可能かを制御するにはcanMoveRowAtIndexPathメソッドを使います。

override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

参考URL

UITableView の編集モードを利用してデータの削除や並び替えを行う - Think Big Act Local