Ios 如何获取uicollectionview的最后一个indexpath?
我想获取uicollectionview的最后一个indexpath 我试过这个:Ios 如何获取uicollectionview的最后一个indexpath?,ios,uicollectionview,nsindexpath,Ios,Uicollectionview,Nsindexpath,我想获取uicollectionview的最后一个indexpath 我试过这个: NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1; NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1; NSIndexPath *lastIndexPath
NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
但找不到uicollectionview的最后一个indexpath
任何建议,
提前感谢。回答Swift 3
NSInteger lastSectionIndex = [tableView numberOfSections] - 1;
NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
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
}
}
}
}
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
}
}
}
}
代码看起来不错。“找不到uicollectionview的最后一个indexpath”是什么意思?
NSLog(@“%@”,indexath)的输出是什么?预期的输出是什么?NSInteger section=[[u collectionView numberOfSections]-1;NSInteger项目=[\u collectionView Number OfItemsInSection:section]-2;nsindepath*lastIndexPath=[nsindepath-indexPathForItem:item-instation:section];这对我来说很好。。。感谢您的评论,为什么不从模型中创建索引路径呢?这会让人感觉更自然,而不是干扰视图。“找不到uicollectionview的最后一个indexpath”是什么意思?NSLog(@“%@”,indexath)的输出是什么?预期的输出是什么?NSInteger section=[[u collectionView numberOfSections]-1;NSInteger项目=[\u collectionView Number OfItemsInSection:section]-2;nsindepath*lastIndexPath=[nsindepath-indexPathForItem:item-instation:section];这对我来说很好。。。感谢您的评论,为什么不从模型中创建索引路径呢?这会让人感觉更自然,而不是干扰视图如果最后一节有0项,则代码>将崩溃。请注意,NSInteger lastRowIndex=[tableView numberofrowsinssection:lastSectionIndex]-1如果最后一节有0项,则代码>将崩溃。