今回は下の写真のように、UITableViewのセルをスワイプした時に表示するボタン(アクション)の追加方法について紹介します。

Contents
実装方法
右から左へのスワイプアクションを追加したい場合は tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) を呼び出す必要があります。
該当する処理だけ抜き出すと次のようになります。
extension ViewController: UITableViewDelegate {
  // スワイプした時に表示するアクションの定義
  func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {         
    // 編集処理
    let editAction = UIContextualAction(style: .normal, title: "Edit") { (action, view, completionHandler) in            
      // 編集処理を記述
      print("Editがタップされた")
    // 実行結果に関わらず記述
    completionHandler(true)
    }        
   // 削除処理
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (action, view, completionHandler) in
      //削除処理を記述
      print("Deleteがタップされた")
      // 実行結果に関わらず記述
      completionHandler(true)
    }
    // 定義したアクションをセット   
    return UISwipeActionsConfiguration(actions: [deleteAction, editAction])
  }
}
上記のコードを記述することで右から左にスワイプした時に「Edit」と「Delete」のアクションボタンが追加されます。
処理はprintしか書いていないので、アプリにあった処理を記述してください。
実際に画面を確認すると、こんな感じです。

補足. UIContextualActionのスタイルについて
UIContextualActionのスタイルに「.destructive」を設定すると、セルを右から左端までスワイプした時に自動で対象のセルが消えるようになります。
ただし、複数のアクションボタンを設定する場合は、UISwipeActionsConfigurationで最初に削除処理(.destructiveを設定したアクション)を追加する必要があります。
// 良い例
return UISwipeActionsConfiguration(actions: [deleteAction, editAction])
// 悪い例
return UISwipeActionsConfiguration(actions: [editAction, deleteAction])
アクションボタンの背景色を変更したい場合
次のように書けば背景色を変更できます。
editAction.backgroundColor = UIColor.blue

アクションボタンに画像を設定したい場合
次のようにimageプロパティに画像を設定すればOKです
editAction.image = UIImage(named: "trash")
左から右にスワイプした時にアクションボタンを表示したい場合
右から左へのスワイプアクションを追加したい場合は tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) 呼び出す必要があります。
なので、先ほどの右から左へのスワイプの時と、呼び出すメソッドが異なります。
extension ViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let editAction = UIContextualAction(style: .normal, title: "Edit") { (action, view, completionHandler) in
      //処理を記述
  
      // 実行結果に関わらず記述
      completionHandler(true)
    }
      return UISwipeActionsConfiguration(actions: [editAction])
  }
}
メソッド内で書く内容は同じです。
画面を確認すると、次のようになります。

(2025/11/03 23:28:25時点 Amazon調べ-詳細)



