使UICollectionViewCell出现在UICollectionView的中心

时间:2013-08-23 16:02:12

标签: ios ios6 uicollectionview uicollectionviewcell

我有一些动态添加到UICollectionView的单元格。我想要做的是更改这些单元格的插图,使它们出现在UICollectionView的中心。这是因为添加单元格高度的单元格越多(单行UICollectionView)。

- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    // This method is used to center when one tile is entered else use a standard no inset
    if (self.wordArray.count == 1) {
        CGFloat newWidth = (self.tileCollectionView.bounds.size.width - self.tileCollectionView.bounds.size.height);
        return UIEdgeInsetsMake(0, (newWidth / 2), 0, (newWidth/2));
    } else {
        return UIEdgeInsetsMake(0, 0, 0, 0); // top, left, bottom, right
    }
}

如何为任何单元格获取UICollectionViewCell当前高度的引用,因为它们的形状都相同(只有它们的高度/宽度会在添加更多单元时继续适合一行时发生变化。< / p>

一旦我得到了细胞高度的参考,我可以添加如下内容: self.tileCollectionView.bounds.size.height - CELLHEIGHT / 2 - 用作单元格的插图。

2 个答案:

答案 0 :(得分:2)

如果您的所有单元格大小相同并假设您使用UICollectionViewFlowLayout,则可以使用此单元格来获取其大小:

UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
CGFloat width = flowLayout.itemSize.width;
CGFloat height = flowLayout.itemSize.height;

这是我使用UICollectionViewFlowLayout计算我的插图的方式:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    NSInteger numberOfCells = self.view.frame.size.width / flowLayout.itemSize.width;
    NSInteger edgeInsets = (self.view.frame.size.width - (numberOfCells * flowLayout.itemSize.width)) / (numberOfCells + 1);
    return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets);
}

您还需要确保在屏幕旋转时使布局无效,以便再次计算新的插图:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.collectionView.collectionViewLayout invalidateLayout];
}

答案 1 :(得分:1)

如果你使用网格式布局,我会试试这个方法: collectionView:layout:sizeForItemAtIndexPath:

您需要实现UICollectionViewFlowLayoutDelegate才能执行此操作。要使它们堆叠,请将最小偏移设置为负数,即单元格本身的大小。这可能需要一些试验和错误。