[TIL] ScrollView 상단으로 올리는 방법

Eden·2025년 9월 11일

iOS 개발에서 UIScrollView 또는 이를 상속한 UITableView, UICollectionView를 사용할 때
화면을 맨 위로 스크롤하는 기능이 자주 필요합니다.


기본 개념

  • UIScrollViewcontentOffset 속성을 이용해 스크롤 위치를 제어합니다.
  • contentOffset.y 값이 작을수록 위쪽, 클수록 아래쪽으로 이동합니다.
  • 단순히 CGPoint(x: 0, y: 0)을 쓰면 safeAreacontentInset 때문에 정확히 맨 위가 아닐 수 있습니다.
  • 따라서 adjustedContentInset.top 을 고려해야 합니다.

구현 예시

private func scrollToTop(animated: Bool = false) {
    let y = -scrollView.adjustedContentInset.top
    scrollView.setContentOffset(CGPoint(x: 0, y: y), animated: animated)
}

코드 설명

  1. adjustedContentInset.top: safeArea나 추가된 inset 값을 포함한 상단 여백
  2. CGPoint(x: 0, y: y): 스크롤 위치를 최상단으로 지정
  3. animated: Bool: 애니메이션 여부를 선택 가능

UITableView / UICollectionView에서도 사용 가능

tableView.setContentOffset(
    CGPoint(x: 0, y: -tableView.adjustedContentInset.top),
    animated: true
)

또는 scrollToRow / scrollToItem 메서드를 사용할 수도 있습니다.

tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: true)

정리

  • scrollView.setContentOffset(_:animated:) 으로 직접 위치 지정 가능
  • 정확한 맨 위를 맞추려면 adjustedContentInset.top을 고려해야 함
  • UITableView, UICollectionView는 별도의 전용 메서드(scrollToRow, scrollToItem)도 제공
profile
iOS Dev

0개의 댓글