Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] UITableView의 편집모드 사용 방법 (셀 삭제, 셀 이동, canEditRowAt, editingStyleForRowAt, commit, canMoveRowAt, moveRowAt) 본문

iOS 응용 (swift)

[iOS - swift] UITableView의 편집모드 사용 방법 (셀 삭제, 셀 이동, canEditRowAt, editingStyleForRowAt, commit, canMoveRowAt, moveRowAt)

jake-kim 2023. 5. 7. 22:58

셀 삭제 기능 활성화 방법

  • UITableView의 편집모드 중 셀 삭제 - UITableView에서 아무것도 설정 안하고 수정모드에 들어가면 UI는 모두 활성화
    • 버튼에서 tap()이 눌렸을 때 tableView.setEditing(animated:)로 편집모드 설정
@objc private func tap() {
    let shouldBeEdited = !tableView.isEditing
    tableView.setEditing(shouldBeEdited, animated: true)
    editButton.isSelected = shouldBeEdited
}
  • 왼쪽에 삭제 UI 버튼이 노출되고, 삭제 버튼을 눌러도 아무런 반응이 없는 상태

  • 셀 삭제 기능 활성화 - delegate 할당
tableView.delegate = self
  • canEditRowAt에서 삭제 UI가 표출될 셀 지정
extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        indexPath.row > 2
    }
}
  • Editing 모드에 들어가면 위에서 true를 리턴한 셀들만 삭제 UI 노출
    • (단, 아직 삭제 버튼을 눌러도 아무런 반응 x)

  • editingStyleForRowAt에서 editing 스타일 지정 (삭제, 추가, none)
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    indexPath.row > 2 ? .delete : .none
}
  • commit 메소드를 추가하면 마침내 delete 버튼을 눌렀을때 오른쪽에 DELETE가 등장
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    
}

  • 데이터소스로 사용하고 있는 배열에서 삭제하고, UI에 있는 셀까지 deleteRows(at:with:)으로 삭제하면 반영 완료
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    guard editingStyle == .delete else { return }
    items.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .fade)
}

셀 이동 기능 활성화 방법

  • canMoveRowAt에서 이동 가능한 셀 지정
    • 아직 여기까지해도 편집모드에 들어갔을때 move 버튼이 보이지 않음
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    indexPath.row > 2
}
  • moveRowAt을 추가하면 마침내 move 버튼(햄버거버튼)이 노출
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    
}
  • 셀을 놓았을 때 특정 셀에는 이동이 안되게끔 하고싶은 경우, targetIndexPathForMoveFromRowAt 추가
// ex) 셀이 위로는 이동 불가능하고 아래로만 이동시킬수 있는 코드
func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
    guard sourceIndexPath.row < proposedDestinationIndexPath.row else { return sourceIndexPath }
    return proposedDestinationIndexPath
}

정리

  • 셀 삭제, 셀 이동 모두 UITableViewDelegate 에서 처리
  • 셀 삭제 활성화
    • canEditRowAt에서 수정 가능한 셀 지정
    • editingStyleForRowAt에서 delete 스타일 지정
    • commit에서 삭제했을때 데이터 소스에 반영
// delegate
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    indexPath.row > 2
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    indexPath.row > 2 ? .delete : .none
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    guard editingStyle == .delete else { return }
    items.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: .fade)
}
  • 셀 이동 활성화
    • canMoveRowAt에서 이동가능한 셀 지정
    • moveRowAt을 선언만해도 move 버튼 (햄버거버튼) 등장
    • targetIndexPathForMoveFromRowAt에서 이동이 안되게끔할 셀 지정
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    indexPath.row > 2
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    
}
// ex) 셀이 위로는 이동 불가능하고 아래로만 이동시킬수 있는 코드
func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
    guard sourceIndexPath.row < proposedDestinationIndexPath.row else { return sourceIndexPath }
    return proposedDestinationIndexPath
}

* 전체 코드: https://github.com/JK0369/ExTableViewEditing

Comments