1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift]TableViewで特定のセルだけ削除できなくするメモ

1
Posted at

今回の題

とある機能の作成過程で配列の先頭(0番目)をデフォルトで持たせておいて、その値は削除できない様にしたかった時に使った方法をここに書き残します。
シンプルな内容です。

やり方

これだけ。
UITableViewDelegateのdelegateメソッドで、各セルのediting styleを設定します。
今回は0番目に対してnoneを当て、それ以外にdeleteを当てる事で0番目だけ削除不可を実装しました。

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    indexPath.row == 0 ? .none : .delete
}

swiftは{}内が一行であればreturnを省略できるので三項演算子を使って書くと良き。
ちなみにif文で書くとこう。

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

以上です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?