如何获取uicollectionview的最后一个indexPath(NOT TABLE VIEW)?需要它做服务器端分页

时间:2017-07-20 07:24:40

标签: ios swift uicollectionview

我已经找到了获取indexPath的最后一个UICollectionView的方法,尽管下面的代码适用于UITableView(有一个部分):

[NSIndexPath indexPathForRow:[yourArray count]-1 inSection:0] 

但未能为UICollectionView实现相同的目标。

4 个答案:

答案 0 :(得分:1)

你可以像这样找到UICollectionView的最后一个索引。

    NSInteger lastSectionIndex = MAX(0, [self.yourCollectionView numberOfSections] - 1);
    NSInteger lastRowIndex = MAX(0, [self.yourCollectionView numberOfItemsInSection:lastSectionIndex] - 1);
    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastRowIndex
                                                inSection:lastSectionIndex];

你也可以像这样找到UITableView的最后一个索引。

    NSInteger lastSectionIndex = MAX(0, [self.yourTableView numberOfSections] - 1);
    NSInteger lastRowIndex = MAX(0, [self.yourTableView numberOfRowsInSection:lastSectionIndex] - 1);
    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:lastRowIndex
                                                inSection:lastSectionIndex];

如果你想检测特定部分的最后一个索引,你只需要用“lastSectionIndex”替换该部分的索引。

答案 1 :(得分:0)

服务器端分页的简单方法(我使用):

您可以在集合/表视图的willDisplay cell:委托方法中进行服务器端分页。

您将获得将要显示的单元格的indexPath,然后创建一个条件,检查显示indexPath.item是否等于dataArray.count-1(dataArray是一个数组,您的集合/表视图已加载)

答案 2 :(得分:0)

我认为,
你应该在scrollView的委托"scrollViewDidEndDecelerating"
中这样做 按

检查您当前可见的单元格
NSArray<NSIndexPath*>* visibleCells = [self.collection indexPathsForVisibleItems];

通过,

创建最后一个indexPath
NSIndexPath* lastIndexPath = [NSIndexPath indexPathForItem:(datasource.count-1) inSection:0];

检查条件,

if([visibleCells containsObject:lastIndexPath]) {
            //This means you reached at last of your datasource. and here you can do load more process from server
        }

整个代码就像,Objective C Code,

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSArray<NSIndexPath*>* visibleCells = [collection indexPathsForVisibleItems];
    NSIndexPath* lastIndexPath = [NSIndexPath indexPathForItem:(Blogs.count - 1) inSection:0];

    if([visibleCells containsObject:lastIndexPath]) {
        //This means you reached at last of your datasource. and here you can do load more process from server
    }
}

Swift 3.1 Code,

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let visibleCells: [IndexPath] = collection.indexPathsForVisibleItems
    let lastIndexPath = IndexPath(item: (Blogs.count - 1), section: 0)
    if visibleCells.contains(lastIndexPath) {
        //This means you reached at last of your datasource. and here you can do load more process from server
    }
}

答案 3 :(得分:0)

斯威夫特 5

extension CLLocationCoordinate2D: Hashable {
    public static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
    }
    
    public func hash(into hasher: inout Hasher) {
        hasher.combine(latitude)
        hasher.combine(longitude)
    }
}