我想获取uicollectionview的最后一个索引路径。
我试过了:
NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
但是找不到uicollectionview的最后一个索引路径。
任何建议, 提前谢谢。
答案 0 :(得分:1)
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
答案 1 :(得分:1)
回答Swift 3
extension UICollectionView {
func scrollToLastIndexPath(position:UICollectionViewScrollPosition, animated: Bool) {
self.layoutIfNeeded()
for sectionIndex in (0..<self.numberOfSections).reversed() {
if self.numberOfItems(inSection: sectionIndex) > 0 {
self.scrollToItem(at: IndexPath.init(item: self.numberOfItems(inSection: sectionIndex)-1, section: sectionIndex),
at: position,
animated: animated)
break
}
}
}
}
请注意,我的经验表明,animated
属性应为false
,用于初始化collectionView。
从上面的代码中,作为您问题的答案,请使用此方法:
func lastIndexPath() -> IndexPath? {
for sectionIndex in (0..<self.numberOfSections).reversed() {
if self.numberOfItems(inSection: sectionIndex) > 0 {
return IndexPath.init(item: self.numberOfItems(inSection: sectionIndex)-1, section: sectionIndex)
}
}
return nil
}