今回の題
とある機能の作成過程で配列の先頭(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
}
以上です。