적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

Swift iOS 앱 개발/Swift

[Swift iOS] UICollectionView scroll to top / bottom

hongssup_ 2021. 10. 13. 10:55
반응형

다음과 같이 옵저버로 호출을 해줘도 되고 버튼 클릭으로 해줘도 되고 암튼 스크롤 top / bottom 함수를 호출해준다

NotificationCenter.default.addObserver(self, selector: #selector(self.scrollToBottom), name: NSNotification.Name(rawValue: "ScrollToBottom"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.scrollToTop), name: NSNotification.Name(rawValue: "ScrollToTop"), object: nil)

 

다음과 같이 맨 위로 / 맨 아래로 스크롤하는 함수를 선언해줄 수 있다. 

@objc func scrollToTop() {
    guard collectionView.numberOfSections > 0 else { return }
    print("스크롤 top: \(collectionView.numberOfSections)")
    collectionView.setContentOffset(.zero, animated: true)
}
@objc func scrollToBottom() {
    guard collectionView.numberOfSections > 0 else { return }
    print("스크롤 bottom: \(collectionView.numberOfSections)")
    let indexPath = IndexPath(item: collectionView.numberOfItems(inSection: collectionView.numberOfSections - 1) - 1, section: collectionView.numberOfSections - 1)
    collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}

 

 

 

 

참고 : StackOverflow - CollectionView scroll to top,

728x90
반응형