[iOS] UITableView scrollToRow, 특정 셀로 스크롤 이동

ungchun·2022년 7월 7일
1
post-thumbnail

이번에 프로젝트를 진행하면서 UITableView 를 사용하다보면 특정 셀로 이동시켜야하는 경우가 생겨서 그 방법을 찾아보다가 정리하면 좋을거 같아서 정리해보려한다.

scrollToRow(at:at:animated:)

사실 방법은 정말 간단하다. 바로 scrllToRow 를 사용하면 되는데 사용법은 다음과 같다.

 	// 날짜 안지난 스토리로 스크롤 이동
  	let startIndex = IndexPath(row: StoryDay().storyArray.firstIndex(of: StoryDay().storyArray.filter 
    { $0 > Int(CoupleTabViewModel.publicBeginCoupleDay)! }.min()!)!, section: 0)
	self.tableView.scrollToRow(at: startIndex, at: .top, animated: false)

사실 코드는 별거 없다. 자신이 원하는 위치의 IndexPath 를 구해서 그 위치로 셀을 이동시켜주면 된다. 주의할 점은 이동시키고 싶은 위치의 index 값을 정확히 알아야하고 at 부분을 .top 으로하면 상단으로 이동하고, .bottom 으로하면 하단으로 이동한다. animated 를 true 로 하면 이동하는 애니메이션이 추가된다. 이 코드는 날짜가 안지난 storyArray value 중에서 가장 작은 value의 위치로 이동시키는 코드이다.

더욱 간단한 코드를 예시로 보면

	let endIndex = IndexPath(row: Message.messages.count - 1, section: 0)
    self.tableView.scrollToRow(at: endIndex, at: .bottom, animated: true)

이 코드는 카카오톡을 사용한다고 생각해보자. message를 보내거나 받으면 그 message 기준으로 스크롤이 이동해야한다. messages.count - 1 row 로 이동하는데 그 index 기준으로 하단으로 이동한다. 이렇게 해석하면 쉽다.

0개의 댓글