LoginSignup
4
3

More than 3 years have passed since last update.

【備忘録】TableViewのセルを右からスワイプすると削除ボタンが出てくる

Posted at

1. 概要

筆者がTableViewのセルを左スワイプするメソッドを追加した時、なぜか設定した覚えのない右スワイプで、「削除」と書かれたボタンが表示されてしまいした。
原因を調べてみるとTableViewの仕様に関する重要なことがわかったので、ここに備忘録として書いておきます。

2. 原因

TableViewには、"isEditing"というプロパティが存在します。
この"isEditing"がtrueの状態(以下、編集モードと呼びます)だと、セルを右からスワイプすることで削除ボタンが出るようになります。

そしてこの"isEditing"を制御するには、TableViewの"editingStyleForRowAt"というメソッドを用います。
"tableView.isEditing"はデフォルトではfalseなので、編集モードとそれ以外で削除ボタンの有無を変えるには、以下のように記述すればOKです。

MyTableViewController
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    if tableView.isEditing {
        return .delete
    }
    return .none
}

しかしここで厄介なのは、"tableView.isEditing"はデフォルトでfalseなのにも関わらず、"editingStyleForRowAt"メソッドを記述しないと、TableViewが常に編集モードになってしまうという仕様です。

ここについては、公式ドキュメントにしっかり書いてありました。

This method allows the delegate to customize the editing style of the cell located atindexPath. If the delegate does not implement this method and the UITableViewCell object is editable (that is, it has its isEditing property set to true), the cell has the UITableViewCell.EditingStyle.delete style set for it.

tableView(_:editingStyleForRowAt:)

つまり、「このメソッドを実装しないとデフォルトで編集モードになるよ」ということです。
僕の場合、編集モードを実装せず削除ボタンも使わないので、以下のように".none"を返すだけの処理を書くことで解決しました。

MyTableViewController
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}

3. 終わりに

筆者はSwift初心者なので、理解不足の点や間違っている箇所もあると思います。
その際にはコメントで指摘していただけると幸いです。

4
3
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
4
3