LoginSignup
19
12

More than 5 years have passed since last update.

TableViewCellの並び替えでドラッグ移動と削除モードの制御方法でハマった。

Last updated at Posted at 2018-03-03

はじめに

Swiftを勉強し始めて半年が経過し、tableViewを使っている時にセルの並び替えの仕方を知らなくて困ったので今回の記事で簡単にまとめます。間違っているところがあれば、コメントお願いします。

環境

XCode Version 9.2
Swift Version 4.0.3

やりたいこと

sampleDemo.gif

サンプルデモのように、セルをドラッグして並び替えしたい。
削除したいセルはないので削除モードはいらない。

ハマった点

ViewController.swift
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
     return true
}

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
     return true
    }

canMoveRowAtcanEditRowAtを両方trueにすることで編集モードとソートモードの両方使えるようになってしまった。
failureDemoQiita1.png

削除はしたくないので、
実装したいのは、並び替える機能だけ。

解決策

以下のコードを追加すると削除モードが無くなった!
全然そんなこと知らなかった。。。

ViewController.swift
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
     return .none
}

func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
     return false
 }

最後に

今回のコードはサンプルとしてgithubに載せています。https://github.com/tomoyamatsuyama/sampleTableViewCellMove

参考文献

【Swift】View Tableの編集モードの使い方。セルの並び替え、削除をする。http://hajihaji-lemon.com/smartphone/swift/uiviewtable-edit/

19
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
12