使用内容插入时,UICollectionView查找中心单元格

时间:2015-05-30 02:58:30

标签: ios objective-c uicollectionview

我正在试图弄清楚如何找到UICollectionView的最中心单元格,该单元格设置为仅水平滚动。

我尝试了这个:how to get indexPath for cell which is located in the center of UICollectionView但是它没有用,我想是因为我使用的是contentInset的{​​{1}}属性。

我正在做的是将流布局的左侧和右侧UICollectionView设置为contentInset的边界宽度减去1/2 self.view宽度的1/2。由于这个原因,我不确定如何计算最中心的单元格。我很感激提供任何帮助。代码:

itemSize

1 个答案:

答案 0 :(得分:0)

我自己使用这个答案的帮助来解决这个问题:https://stackoverflow.com/a/22696037/1533438

最终代码:

- (void)snapCollectionView:(UICollectionView *)collectionView withProposedOffset:(CGPoint)proposedOffset
{
    CGRect cvBounds = collectionView.bounds;
    CGFloat halfWidth = cvBounds.size.width * 0.5;
    CGFloat proposedContentOffsetCenterX = proposedOffset.x + halfWidth;

    NSArray *attributesArray = [collectionView.collectionViewLayout layoutAttributesForElementsInRect:cvBounds];

    UICollectionViewLayoutAttributes *candidateAttributes;

    for (UICollectionViewLayoutAttributes *attributes in attributesArray)
    {
        if (attributes.representedElementCategory !=
            UICollectionElementCategoryCell)
        {
            continue;
        }

        if (!candidateAttributes)
        {
            candidateAttributes = attributes;
            continue;
        }

        if (fabsf(attributes.center.x - proposedContentOffsetCenterX) <
            fabsf(candidateAttributes.center.x - proposedContentOffsetCenterX))
        {
            candidateAttributes = attributes;
        }
    }

    CGPoint offset = CGPointMake(candidateAttributes.center.x - halfWidth, proposedOffset.y);
    [collectionView setContentOffset:offset animated:YES];

    CGPoint cellCenter = CGPointMake(offset.x + self.sampleCollectionView.bounds.size.width / 2.0, self.sampleCollectionView.bounds.size.height / 2.0);

    NSIndexPath *indexPath = [self.sampleCollectionView indexPathForItemAtPoint:cellCenter];

    if (indexPath)
    {
        NSInteger tag = [self.sampleCollectionView cellForItemAtIndexPath:indexPath].tag;

        if (tag != self.currentSample)
        {
            self.currentSample = tag;

            UIImage *image;

            if (self.currentSample == 0)
            {
                image = self.image;
            }
            else
            {
                image = [self sampleImageWithOption:self.currentSample];
            }

            dispatch_async(dispatch_get_main_queue(),
            ^{
                self.imageView.image = image;
            });
        }
    }
}
相关问题