[iOS] TableViewCell row를 밀어서 삭제하기

Logan·2020년 12월 11일
2

테이블뷰 셀을 밀어서 삭제하려면, 셀에 편집 액션을 적용해야합니다.

방법 1. tableView(_:editingStyleForRowAt:)

func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .delete }

TableViewDelegate를 채용한 다음, 위의 Method를 구현합니다.
return 값으로 UITableViewCell.EditingStyle 타입을 전달합니다.
EditingStyle에는 .none, .delete, .insert 세 가지 값이 열거형으로 저장되어 있습니다.

삭제를 위해 .delete 값을 전달합니다.

그 다음 tableView(__:commit:forRowAt:) Method를 구현합니다.

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
	if editingStyle == .delete { /*예시: tableView.deleteRows(at: [indexPath], with: .automatic)*/ }
}
     

수신자에서 지정된 행의 삽입 또는 삭제를 커미트하도록 데이터 소스에 요청합니다.
삭제를 구현해야하기 때문에 만약 editingStyle이 .delete일 경우 코드를 실행하도록 Method안에 조건문을 추가합니다.


방법 2. tableView(_:trailingSwipeActionsConfigurationForRowAt:)

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
       let action = UIContextualAction(style: .normal, title: nil) { (action, view, completion) in
       	    tableView.deleteRows(at: [indexPath], with: .automatic)
            completion(true)
        }
        
        action.backgroundColor = .white
        action.image = #imageLiteral(resourceName: "DeleteIcon")

        let configuration = UISwipeActionsConfiguration(actions: [action])
        configuration.performsFirstActionWithFullSwipe = false
        return configuration
   }

tableView(_:trailingSwipeActionsConfigurationForRowAt:) Method를 구현하는 방법입니다.
Method 내부에서 UIContextualAction 인스턴스를 만들어줍니다. (style과 title 지정)
UIContextualAction handler 부분에서 삭제하는 코드를 구현합니다.

추가로 버튼의 배경이나 이미지를 추가할 수도 있습니다.
만약 Cell의 높이가 충분하지 않다면, UIContextualAction에서 지정했던 title은 표시되지 않습니다.

Method를 하나만 구현하면 되고 자유롭게 버튼을 디자인할 수 있다는 장점이 있습니다.
또 Cell의 앞쪽에서 사용하고 싶다면, tableView(:leadingSwipeActionsConfigurationForRowAt:)_ Method를 사용하면 됩니다.


방법 3? tableView(_:editActionsForRowAt:)

동일한 기능을 하는 tableView(__:editActionsForRowAt:) Method가 있지만, iOS 13 버전 이상부터 Deprecated 되었기때문에 사용을 권장하진 않습니다.


주의할 점

예제 코드에서는 정확하게 구현하지 않았지만, TableView.deleteRows(at:with:)을 호출하기 전엔 반드시 연동되어있는 데이터도 함께 지워준 다음 호출해야 합니다.

profile
iOS개발자 꿈나무

0개의 댓글