본문 바로가기
iOS/Swift

[Swift] UITableView, UICollectionView Last IndexPath

by Jiseong 2023. 12. 5.

TableView 마지막 인덱스

private extension UITableView {
    func lastIndexPath() -> IndexPath {
        let section = max(numberOfSections - 1, 0)
        let row = max(numberOfRows(inSection: section) - 1, 0)
		
        return IndexPath(row: row, section: section)
    }
}

 

CollectionView 마지막 인덱스

private extension UICollectionView {
    func lastIndexPath() -> IndexPath {
        let section = max(numberOfSections - 1, 0)
        let row = max(numberOfItems(inSection: section) - 1, 0)
		
        return IndexPath(row: row, section: section)
    }
}

 

numberOfSections, numberOf ... 은 갯수를 의미하기에 IndexPath를 생성하려면 -1을 해줘야한다.

 

혹여나 numberOfSections, numberOf ... 가 0이여서 -1을 하면 음수를 반환할 수 있기때문에, 0으로 예외처리를 했다.

 

사용

// 인덱스 검증
if indexPath.row == tableView.lastIndexPath().row {
    // ...
}

// 컬렉션뷰 사이즈 업데이트
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    let lastIndex = collectionView.lastIndexPath().row
    let numberOfRows = latsIndex / 셀 행수(열수) + 1
    // lineSpacing 로직
    
    // Layout Update 로직
}

 

'iOS > Swift' 카테고리의 다른 글

[iOS] View Drawing Cycle (Layout까지 작성함)  (0) 2022.08.07
[Xcode] 단축키 좀 써주세요...  (0) 2022.08.06
[Swift] defer  (0) 2022.06.10
[Swift] mutating  (2) 2022.05.08
[Swift] Hashable  (0) 2022.05.02

댓글