iOS 개발에서 UIScrollView 또는 이를 상속한 UITableView, UICollectionView를 사용할 때
화면을 맨 위로 스크롤하는 기능이 자주 필요합니다.
UIScrollView는 contentOffset 속성을 이용해 스크롤 위치를 제어합니다.contentOffset.y 값이 작을수록 위쪽, 클수록 아래쪽으로 이동합니다.CGPoint(x: 0, y: 0)을 쓰면 safeArea나 contentInset 때문에 정확히 맨 위가 아닐 수 있습니다.adjustedContentInset.top 을 고려해야 합니다.private func scrollToTop(animated: Bool = false) {
let y = -scrollView.adjustedContentInset.top
scrollView.setContentOffset(CGPoint(x: 0, y: y), animated: animated)
}
adjustedContentInset.top: safeArea나 추가된 inset 값을 포함한 상단 여백CGPoint(x: 0, y: y): 스크롤 위치를 최상단으로 지정animated: Bool: 애니메이션 여부를 선택 가능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)도 제공