LoginSignup
43
39

More than 5 years have passed since last update.

UITableViewで常にCellの並び替え(ソート)ができるようにする

Posted at

概要

編集モードをユーザーが選ぶことなしに、常に並び替え(ソート)ができるUITableViewを実装したメモです。

スクリーンショット

ソースコード

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.isEditing = true
        tableView.allowsSelectionDuringEditing = true
    }
}

extension ViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "Item \(indexPath.row)"
        return cell
    }

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

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

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

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

ポイント

  • viewDidLoadでtableView.isEditing = trueを呼ぶ
  • canMoveRowAtmoveRowAtを実装すると、並び替えができるようになる
  • editingStyleForRowAtshouldIndentWhileEditingRowAtで見た目を制御
  • Cellをタップ選択できるようにするには、tableView.allowsSelectionDuringEditing = trueをviewDidLoadで読んでおく

以上で編集モードをユーザーが選ぶことなしに、Cellの並び替えがいつでもできるTableViewができました。

43
39
2

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
43
39