获取collectionview或tableView 中当前展示的cell

 

之前我都是用UItableView 获取当前展示的cell都是写在 tableView: cellForIndexpath中获取,但是在现在在UICollectionView中的某些情况下出现bug

有些人直接使用 

NSArray *array = [collectionView visibleCells];

UICollectionView *cellShow = array.firstObject; //获取的cell不完成正确,cell有可能有多,有的正在消失,有的正在出现

需要在下面方法中获取,否则,在滑动过程中,是无法获取到的,也不正确。

-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView

 

 

下面是我自己的获取方法:支持在滑动过程中获取将要占主屏幕的cell

思路:由于cell 在屏幕中出现可能有多个,且在collection分页设置时有弹性,判断cell 在屏幕中出现的面积大于一半,在弹性的作用下默认会展示!


#pragma mark - 滑动的时候监听cell的变化

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

    [self delegateShowCell:_albumCollectionView];

}

 

#pragma mark - 当前出现在collectionview中的cell代理回调

-(void) delegateShowCell:(UICollectionView *)collectionView{

    //当前出现的cell

    if (_delegate != nil && [_delegate respondsToSelector:@selector(albumView:LayoutItemAtIndexPath:)]) {

        CGFloat x = collectionView.frame.origin.x;

        CGFloat y = collectionView.frame.origin.y;

        CGFloat xWidth = collectionView.frame.size.width + x;

        CGFloat yHeight = collectionView.frame.size.height + y;

        NSArray *array = [collectionView visibleCells]; //获取的cell不完成正确

        if(array != nil && array.count > 0){

            UIView *cell1 = array.firstObject;

            if (array.count == 1) {

//当前的cell

                [_delegate albumView:self LayoutItemAtIndexPath:[NSIndexPath indexPathForRow:cell1.tag inSection:0]];

            }else{

                //origin.x 出现的cell

                CGRect frame1 = [cell1 convertRect:cell1.bounds toView:collectionView.superview];

                //判断位置是否出现在当前collectionView内cell的面积大约一半

                if (xWidth - frame1.origin.x > xWidth/2 && yHeight - frame1.origin.y > yHeight/2){

//当前的cell

                    [_delegate albumView:self LayoutItemAtIndexPath:[NSIndexPath indexPathForRow:cell1.tag inSection:0]];

                }

                //origin.x 消失cell

                UIView *cell2 = array.lastObject;

                CGRect frame2 = [cell2 convertRect:cell2.bounds toView:collectionView.superview];

                if ( frame2.origin.x + frame2.size.width - x > xWidth/2 && frame2.origin.y + frame2.size.height - y > yHeight/2){

//当前的cell

                    [_delegate albumView:self LayoutItemAtIndexPath:[NSIndexPath indexPathForRow:cell2.tag inSection:0]];

                }

            }

        }

    }

}

//说明:collectionview在滑动的过程中,cell的位置是发生变化的,因此,什么时候获取很重要!而且cell可能有多个!

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值