こんにちは、nukkyです。
今回は、UITableViewでセルを入れ替えたい際に、ドラッグ&ドロップ操作を簡単に実装できるライブラリ「SwiftReorder」を紹介したいと思います。
今回はCocoaPodsを使いたいと思います。
Podfileに以下を追加してください。
pod 'SwiftReorder', '~> 3.0'
追加したらターミナルから以下のコマンドを実行してください。
pod install
まずは「SwiftReorder」をインポートします
import SwiftReorder
テーブルビューを実装したいコントローラーに以下を継承します
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
StoryboardにUITableViewを設置し、コード上のIBOutletに紐づけてください
@IBOutlet weak var tableView: UITableView!
UITableViewのセルに表示するテキストを宣言します
今回は並べ替えがわかりやすい様にナンバリングしたいと思います
var items = (1...10).map { "Item \($0)" }
tableViewの初期化をViewDidLoadで行います
// SwiftReorderのTableViewReorderDelegate tableView.reorder.delegate = self // delegateの初期化 tableView.dataSource = self tableView.delegate = self // セルの初期化 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
UITableViewのrowとSectionを設定をします
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 }
セルの表示を設定します、ここで先ほど宣言したitemsを表示する様にします
また、表示が更新されない様にドラッグされているセルを最初に返します
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // ドラッグされているセルを返す if let spacer = tableView.reorder.spacerCell(for: indexPath) { return spacer } let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = items[indexPath.row] return cell }
extensionでTableViewReorderDelegateを設定します
ここでドラッグ中のセルの更新処理を書いてます
extension ViewController: TableViewReorderDelegate { func tableView(_ tableView: UITableView, reorderRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { // Update data model let item = items[sourceIndexPath.row] items.remove(at: sourceIndexPath.row) items.insert(item, at: destinationIndexPath.row) } }
sourceIndexPathにドラッグ中のセルのindexPathが、
destinationIndexPathに移動先のindexPathが入っているので
その情報に習ってmodelを入れ替えています。
実行すると、以下の様な動きができるようになっていると思います
「SwiftReorder」いかがでしょうか、
この様な動きを自前で用意するのは面倒なので、ここまで簡単に実装できると便利だと思います。