[iOS] 테이블뷰 셀 순서 변경

RudinP·2024년 5월 2일
0

Study

목록 보기
225/227

Reorder Control

  • 셀의 위치를 변경할 수 있다는 인디케이터

MoveRowAt

  • UITableViewDataSource를 상속하는 곳에서 moveRowAt 델리게이트 메소드를 작성해주면 셀의 위치를 이동할 수 있다.
  • 다만, 이렇게 한다고 이동한 셀에 맞춰 테이블뷰의 데이터가 변경되는 것이 아니기 때문에, 위치가 변경된 셀이 안보일 때까지 스크롤한뒤에 다시 돌아오면 기존의 순서에 기반했던 데이터의 셀이 중복으로 보이게 된다.
  • 즉, 실제 데이터의 위치도 바꾸어주어야 한다.

실제 데이터의 위치도 바꾸어주기

sourceIndexPath로 시작 위치가 전달되고, destinationIndexPath로 이동할 위치가 전달된다.

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let target = list.remove(at: sourceIndexPath.row)
        
        list.insert(target, at: destinationIndexPath.row)
    }
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글