【问题标题】:How to get the last indexpath of a uicollectionview?如何获取 uicollectionview 的最后一个索引路径?
【发布时间】:2015-02-19 19:21:39
【问题描述】:

我想获取 uicollectionview 的最后一个 indexpath。

我试过了:

 NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1;
NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];

但找不到 uicollectionview 的最后一个索引路径。

任何建议, 提前致谢。

【问题讨论】:

  • 代码看起来没问题。 “找不到 uicollectionview 的最后一个索引路径”是什么意思? NSLog(@"%@", indexPath) 的输出是什么?预期的输出是什么?
  • NSInteger section = [_collectionView numberOfSections] - 1 ; NSInteger item = [_collectionView numberOfItemsInSection:section] - 2 ; NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section] ;这对我来说很好......感谢您的评论
  • 你为什么不从你的 model 创建索引路径呢?这样会感觉更自然,而不是弄乱 view

标签: ios uicollectionview nsindexpath


【解决方案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];

【讨论】:

  • 注意NSInteger lastRowIndex = [tableView numberOfRowsInSection:lastSectionIndex] - 1;如果最后一节有0个项目会崩溃。
【解决方案2】:

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2016-02-16
    • 2011-12-14
    相关资源
    最近更新 更多