반응형
tableView에서 셀을 밀어서 삭제하는 방법이 몇가지 있는데 그중에서 trailingSwipeActionsConfigurationForRowAt 메서드를 이용하여 셀을 삭제하려고 한다.
1. tableView delegate 채택하기
class YourViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
2. 스와이프 하고싶은 방향으로 메서드 정의
// 오른쪽 -> 왼쪽으로 밀기
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath)
// 왼쪽 -> 오른쪽으로 밀기
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath)
내 경우에는 여러개의 viewController 에 사용하기 위해서 헬퍼로 따로 만들었다.
extension YourViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let config = DeleteActionConfiguration(todoManager: todoManager, tableView: tableView, indexPath: indexPath, date: Date(), data: nil, updatable: self)
let deleteAction = TableViewHelper.createDeleteAction(config: config) { success in
if !success { print("삭제중 오류발생") }
}
TableViewHelper.configureDeleteActionAppearance(deleteAction)
return UISwipeActionsConfiguration(actions: [deleteAction])
}
}
UIContextualAction 을 생성해서 style 과 title 을 정해주고 핸들러 부분에 구현할 코드를 적어 버튼을 만들어준다.
final class TableViewHelper {
static func createDeleteAction(
config: DeleteActionConfiguration,
completion: @escaping (Bool) -> Void) -> UIContextualAction {
let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completionHandler) in
var deleteTodoData: TodoData
// 1.삭제할 데이터 가져오기 - isSearchBarActive 중에는 날짜가아닌 데이터로 지워야해서 두가지경우로
if config.data == nil {
deleteTodoData = config.todoManager.getParticularTodoData(date: config.date)[config.indexPath.row]
} else {
deleteTodoData = config.data!
}
// 2. 코어데이터에서 삭제
config.todoManager.deleteToDo(data: deleteTodoData)
// 3. 각 뷰컨에 맞게 UI 업데이트
config.updatable.updateAfterDeletion(at: config.indexPath, date: config.date)
// 4. 삭제된 데이터가 마지막 행이 아닐경우 삭제된 행 뒤부터 오더번호 업데이트
if config.indexPath.row < config.todoManager.getParticularTodoData(date: config.date).count {
TodoOrderManager.updateOrder(date: config.date, startIndex: config.indexPath.row, todoManager: config.todoManager)
}
// 작업 완료 처리
completionHandler(true)
completion(true)
}
return deleteAction
}
//셀 삭제버튼 색상, 이미지 설정
static func configureDeleteActionAppearance(_ action: UIContextualAction) {
action.backgroundColor = UIColor.red
action.image = UIImage(systemName: "trash.fill")
}
}
반응형