관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] NSNotFound로 안전하게 IndexPath 접근하는 방법 (# scrollToRow, #IndexPath) 본문

iOS 응용 (swift)

[iOS - swift] NSNotFound로 안전하게 IndexPath 접근하는 방법 (# scrollToRow, #IndexPath)

jake-kim 2024. 2. 14. 01:47

scrollToRow

  • UIScrollView에서 제공하는 scrollToRow(at:at:animated:)라는 메소드를 활용하여 scrollToTop, scrollToBottom과 같은 것을아래처럼 호출이 가능
tableView.scrollToRow(at: .init(row: 0, section: 0), at: .top, animated: true)
  • 하지만 scrollToTop을 위해 위처럼 작성할 경우 IndexPath의 row값이 없는 경우 크래시가 발생
// terminating due to uncaught exception of type NSException
tableView.scrollToRow(at: .init(row: 0, section: 0), at: .top, animated: true)

NSNotFound 파라미터 사용

  • scrollToRow(at:at:animated:) 애플 문서에 NSNotFound를 row에 넣으면 크래시가 없이 안전한 스크롤 구현이 가능

https://developer.apple.com/documentation/uikit/uitableview/1614997-scrolltorow

  • 구현
tableView.scrollToRow(at: .init(row: NSNotFound, section: 0), at: .top, animated: true)

 

* 전체 코드: https://github.com/JK0369/ExNSNotFound

* 참고

- https://developer.apple.com/documentation/uikit/uitableview/1614997-scrolltorow

Comments