UICollectionView 当前可见单元格索引 [英] UICollectionView current visible cell index

查看:41
本文介绍了UICollectionView 当前可见单元格索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在 iPad 应用程序中使用 UICollectionView.我已经设置 UICollectionView 使其大小和单元格大小相同,这意味着一次只显示一次单元格.

I am using UICollectionView first time in my iPad application. I have set UICollectionView such that its size and cell size is same, means only once cell is displayed at a time.

问题:现在,当用户滚动 UICollectionView 时,我需要知道哪个单元格可见,我必须在更改时更新其他 UI 元素.我没有为此找到任何委托方法.我怎样才能做到这一点?

Problem: Now when user scroll UICollectionView I need to know which cell is visible I have to update other UI elements on change. I didn't find any delegate method for this. How can I achieve this?

代码:

[self.mainImageCollection setTag:MAIN_IMAGE_COLLECTION_VIEW];
[self.mainImageCollection registerClass:[InspirationMainImageCollectionCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[self.mainImageFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.mainImageFlowLayout setMinimumInteritemSpacing:0.0f];
[self.mainImageFlowLayout setMinimumLineSpacing:0.0f];
self.mainImageFlowLayout.minimumLineSpacing = 0;
[self.mainImageCollection setPagingEnabled:YES];
[self.mainImageCollection setShowsHorizontalScrollIndicator:NO];
[self.mainImageCollection setCollectionViewLayout:self.mainImageFlowLayout];

我尝试过的:

由于 UICollectionView 符合 UIScrollView,当用户滚动结束时我得到 UIScrollViewDelegate 方法

As UICollectionView conforms to UIScrollView, I got when user scroll ends with UIScrollViewDelegate method

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

但是在上面的函数中,如何获取UICollectionView的当前可见单元格索引?

But inside above function how can I get current visible cell index of UICollectionView ?

推荐答案

[collectionView visibleCells] 方法给你所有你想要的visibleCells 数组.想拿的时候用

The method [collectionView visibleCells] give you all visibleCells array you want. Use it when you want to get

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    for (UICollectionViewCell *cell in [self.mainImageCollection visibleCells]) {
        NSIndexPath *indexPath = [self.mainImageCollection indexPathForCell:cell];
        NSLog(@"%@",indexPath);
    }
}

更新到 Swift 5:

Update to Swift 5:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    for cell in yourCollectionView.visibleCells {
        let indexPath = yourCollectionView.indexPath(for: cell)
        print(indexPath)
    }
}

这篇关于UICollectionView 当前可见单元格索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆