UICollectionView垂直居中

我有一个UICollectionView对象的大小(320,500)。

我需要创build一个内容垂直居中的UICollectionView 。 意思是说,如果内容的总大小是(100,100),那么单元格应该绘制自己的矩形(0,200):(320,300)。 即在50以上,在垂直中心以下250以下50。

问题是单元的数量和单元的大小只在运行时决定。 例如,如果在单元格中的文本可以是1行的大小〜(100,50)。 如果是4行大小将是〜(100,200)。 所以只有在我运行了collectionView:sizeForItemAtIndexPath:之后,才能确定最后一个单元格应该是第一个单元格的起始位置。

任何开始的build议我应该如何处理这个问题。 即使我FlowlayoutFlowlayout ,在绘制最后一个单元格之前,我将如何知道第一个单元格的位置?

你可以使用insetForSectionAtIndex委托方法来中心单元格:

 #pragma mark collection view cell paddings - (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { float leftInset = (self.view.frame.size.width - (COUNT_OF_CELL*WIDTH_OF_CELL + COUNT_OF_CELL-1 * SPACE_BETWEEN_CELLS)) / 2; return UIEdgeInsetsMake(0, leftInset, 0, 0); // top, left, bottom, right } - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section { return 8; // this is SPACE_BETWEEN_CELLS } 

您必须更改COUNT_OF_CELL(这是您的数组的计数),WIDTH_OF_CELL,SPACE_BETWEEN_CELLS,它将工作,如你所愿

我是如何通过获取集合视图中最后一个元素的布局属性,然后决定视图的contentInsets。 它的问题是插入的变化不平滑,因为没有animation,但其他明智的作品。

 -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect { NSArray* array = [super layoutAttributesForElementsInRect:rect]; UICollectionViewLayoutAttributes* att = [array lastObject]; if (att){ CGFloat lastY = att.frame.origin.y + att.frame.size.height; CGFloat diff = self.collectionView.frame.size.height - lastY; if (diff > 0){ UIEdgeInsets contentInsets = UIEdgeInsetsMake(diff/2, 0.0, 0.0, 0.0); self.collectionView.contentInset = contentInsets; } } return array; }