[TIL] 2021.06.17


✅⠀TableView Cell Swipe Action


UITableViewDelegateを使用する場合

  • Table Viewに接続されているデータを削除すると、Table Viewになります.deleteRows(at:,with:)を呼び出す必要があります.
  • extension ViewController: UITableViewDelegate{
        func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
            guard indexPath.item > 0 else { return nil }
            
            let delete = UIContextualAction(style: .normal, title: nil) { (action, view, completion) in
                self.num -= 1 // 데이터 삭제 후 
                tableView.deleteRows(at: [indexPath], with: .automatic) // 호출 
                completion(true)
            }
            
            delete.backgroundColor = .red
            delete.title = "삭제"
            
            let insert = UIContextualAction(style: .normal, title: nil) { (action, view, completion) in
                self.num += 1
                tableView.reloadData()
                completion(true)
            }
            
            insert.title = "삽입"
            
            
            let configuration = UISwipeActionsConfiguration(actions: [delete, insert])
            configuration.performsFirstActionWithFullSwipe = false
            return configuration
        }
    }
  • 左、右ともに実現可能.
  • // leadingSwipe
    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) 
    // trailing Swipe
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath)

    RxCocoaを使用する場合

    tableView.rx.itemDeleted
             .subscribe(onNext: { [weak self] indexPath in
                self?.finedustListViewModel.removeFineDust(indexPath.item)
             })
             .disposed(by: disposeBag)