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

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

有些人直接使用 

NSArray *array = [collectionView visibleCells];

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

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

-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView



下面是我自己的获取方法:支持在滑动过程中获取将要占主屏幕的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) {

                [_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){

                    [_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){

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

                }

            }

        }

    }

}

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

猜你喜欢

转载自blog.csdn.net/talinboy/article/details/80375213