본문 바로가기

이상/iOS

[iOS] UITableViewCell Swipe Delete

반응형

예전에 UITableView의 EditingModeSwipeActions에 대해 글을 작성했었다.

 

지금 진행 중인 개인 프로젝트에서 UITableViewCell을 스와이프하여 해당 로우를 삭제하는 기능이 필요한데

 

두 글에서는 너무 잡기능이 많고 정신없어서 간단하게 자주 쓰이는 Swipe Delete 기능만 기록한다.

 

 

Right-to-Left Swipe Delete

 

 

 

DataSource Instance Method 구현

 

Swipe Delete를 사용하기 위해

 

UITableViewDataSource의 tableView(_:canEditRowAt:), tableView(_:commit:forRowAt:) 

 

두 가지를 구현해준다.

 

1
2
3
4
5
6
7
8
9
10
// Row Editable true
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}
// Swipe Right-to-left
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if (editingStyle == .delete) {
        self.viewModel.exerciseVM.remove(at: indexPath.row)
    }
}
cs

 

canEditRowAt은 return true,

 

commit forRowAt은 (editingStyle이 delete일 경우) 처리할 부분을 구현한다.

 

전에 EditingMode 글을 작성하다가 '왜 자동으로 Swipe Delete가 되는거지?'라고 생각했었다.

 

tableView에 대해 editingStyle을 delete로 지정하지 않았는데도 Swipe Delete가 되는 이유는

 

tableView(_:editingStyleForRowAt:) 때문이다.

 

Apple Doc에서 보면 아래와 같이 나와있다.

 

 

tableView(_:editingStyleForRowAt:) Discussion

 

 

tableView(_:editingStyleForRowAt:)를 구현하지 않으면 cell의 editingStyle을 delete로 set 한다고 한다.

 

결국 UITableView의 Cell Swipe Delete 기능을 구현하기 위해서는

 

tableView(_:canEditRowAt:), tableView(_:commit:forRowAt:) 두 인스턴스 메소드만 구현해주면 된다.

 

끝.

 

 

한동안 안드로이드 개발만 하다가

 

다시 iOS 개발을 하니 새로운 기분이 들고 너무 재밌다.

반응형