LoginSignup
0
2

More than 3 years have passed since last update.

[Swift]UITableViewのDrag&Dropでセル連結できる

Posted at

はじめに

UITableViewCellを長押しで並び替えできるようにDrag&Dropを実装しました。
https://qiita.com/king_of_morita/items/815e78d7d285a8d1190c

ところがDragしたセルを他のセルの上に移動すると右上にプラスアイコンが表示されて、Dropでセルの文字が連結されてしまいます。
セルの連結ができる機能があるのはいいですが、今回は不要なのでセルの連結ができないようにする方法を調べました。

RocketSim Recording - iPhone 12 Pro Max - 2020-12-17 22.24.20.gif

セル連結できないように修正後

セルの上にDragしてもプラスアイコンが表示されずに、セル連結できないようになっています。

セル連結できないように修正後

セルの上にDragしてもプラスアイコンが表示されずに、セル連結できないようになっています。

修正コード

UITableViewにUITableViewDragDelegate、UITableViewDropDelegateを設定していますが、
実装自体はなくてもOKで、並び替えの処理はtableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)
で実装します。

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

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
      // ここに並び替えのデータ更新処理を書きます
    }
}

// UITableViewにUITableViewDragDelegate、UITableViewDropDelegateを設定します
func initTableView() {
    tableView.dragInteractionEnabled = true
    tableView.dragDelegate = self
    tableView.dropDelegate = self
}

extension HomeViewController: UITableViewDragDelegate {
    func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        return []
    }
}
extension HomeViewController: UITableViewDropDelegate {
    func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
      // 中身は不要
    }
}

まとめ

検索するとロングプレスでのDrag&Dropの実装方法は見つかりますが、意外な盲点がありました。
なにか参考になれば幸いです。

参考サイト

0
2
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
0
2