【Swift4】UITableViewで常時並べ替え可能にする。

参考サイト
UITableViewで常にCellの並び替え(ソート)ができるようにする – Qiita
UITableViewのデリゲートメソッドまとめ – Qiita

viewDidLoadに下記を追加して常時編集状態にする。
tableView.isEditing = true
tableView.allowsSelectionDuringEditing = true

並べ替え可能にするメソッド。
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}

並べ替え結果を処理するメソッド。
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// TODO: 入れ替え時の処理を実装する(データ制御など)
}

編集状態の見た目を編集する。
//左側の+やーを表示
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none //表示させない。
}
//編集モード時に左にずれるか。
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false //ずれない。
}

これらを前回の記事
【Swift4】UITableViewの基本のき。 | iPhoneアプリ備忘録
に適用すると。

起動すると
Simulator Screen Shot - iPhone X - 2019-03-14 at 10.47.40
この様な感じでいつでも並べ替え可能になる。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です