カテゴリー: iOS

[Swift]UITableViewのセルの入れ替えが簡単に実装できるライブラリ「SwiftReorder」

はじめに

こんにちは、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」いかがでしょうか、
この様な動きを自前で用意するのは面倒なので、ここまで簡単に実装できると便利だと思います。

nukky

シェア
執筆者:
nukky
タグ: Swift

最近の投稿

フロントエンドで動画デコレーション&レンダリング

はじめに 今回は、以下のように…

3週間 前

Goのクエリビルダー goqu を使ってみる

はじめに 最近携わっているとあ…

1か月 前

【Xcode15】プライバシーマニフェスト対応に備えて

はじめに こんにちは、suzu…

2か月 前

FSMを使った状態管理をGoで実装する

はじめに 一般的なアプリケーシ…

3か月 前